从文本文件返回列表列表

时间:2012-11-28 14:55:56

标签: python-3.x

results = open(filename, 'r')


   line = results.readline()
   while line != '':
    # results for a single draw
    star = line[line.rfind('\t') :]
    stars.append(star)
    line =results.readline()
'''

while line != '':


   main = [line[:line.rfind('\t')]]
   mains.append(main)
   line =results.readline()
return (mains)

我正在使用上面的脚本以1,2,3,4,5标签9,10新行6,7,8,9,10标签11,12的格式从文本文件中读取并试图获取回[[1,2,3,4,5],[6,7,8,9,10]]上面的剧本给了我[['1,2,3,4,5'],['6, 7,8,9,10']] - 括号阻止我使用数据。请原谅我再次愚蠢,但如何从文本文件中获取列表格式?我确实尝试阅读其他帖子,但未能应用这些建议 - 对此太新了 非常感谢您的帮助

2 个答案:

答案 0 :(得分:3)

试试这个:

results = open(filename, 'r')
line = results.readline()
mains = []
while line != '':
  stars = line[:line.rfind('\t')].split(',')
  nums = [int(n) for n in stars]
  mains.append(nums)
  line =results.readline()

答案 1 :(得分:0)

尝试:

# say your data is in file named 'testfile'
$ cat testfile 
1,2,3,4,5   9,10
6,7,8,9,10  11,12

# the actual code
datafile = [line.strip().split('\t')[0].split(',') for line in open('testfile')]   
result = []
for l in datafile:
    result.append([int(string) for string in l])
# test the results
print(result)
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]

修改: 要获取每行的两个部分,请尝试:

datafile = [line.strip() for line in open('testfile')]
datafile = [line.split('\t') for line in datafile if line]
datalist = list(zip(*datafile))
result = []
for index in datalist:
    for i in index:
        result.append([int(string) for string in i.split(',')])
# you can access the result list by indexing:
print(result[:2], result[2:])
# or assign to new lists:
firstlist, secondlist = result[:2], result[2:]
print(firstlist, secondlist)