- 论坛徽章:
- 6
|
假设你的题意是每列中的名字和其余数据相对应,用字典实现- test@ubuntu:~/Python$ cat text.txt
- name1 name2 name5
- 1 3 6
- 2 9 6
- 4 9 3.2
- 6 9 1
- test@ubuntu:~/Python$ python
- Python 2.7.10 (default, Oct 14 2015, 16:09:02)
- [GCC 5.2.1 20151010] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> result = {}
- >>> lineList = []
- >>> with open('text.txt') as f:
- ... lines = f.readlines()
- ... for line in lines:
- ... lineList.append(line.strip().split())
- ... print "\n-------\n",lines,"\n-------\n"
- ... titles = lineList[0]
- ... for j in xrange(len(titles)):
- ... result[titles[j]] = []
- ... for i in xrange(1, len(lineList)):
- ... for j in xrange(len(titles)):
- ... result[titles[j]].append(lineList[i][j])
- ...
- -------
- ['name1 name2 name5\n', '1 3 6\n', '2 9 6\n', '4 9 3.2\n', '6 9 1\n']
- -------
- >>> print result
- {'name5': ['6', '6', '3.2', '1'], 'name2': ['3', '9', '9', '9'], 'name1': ['1', '2', '4', '6']}
- >>>
复制代码 |
|