0
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,10new line 6,7,8,9,10 tab 11,12 的文本文件中读取并试图返回 [[ 1,2,3,4,5],[6,7,8,9,10]]上面的脚本给了我 [['1,2,3,4,5'],['6,7,8 ,9,10']] -括号阻止我使用数据。请原谅我再次愚蠢,但是如何从文本文件中获取列表格式?我确实尝试阅读其他帖子,但无法应用这些建议-对此太陌生了非常感谢您的帮助

4

2 回答 2

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()
于 2012-11-28T15:26:43.830 回答
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)
于 2012-11-28T18:38:23.613 回答