在Python中将数字行读入列表

时间:2018-02-23 08:10:09

标签: python python-2.7

我正在尝试将两行从一个文件读入两个列表,这样每行都在一个列表中。

data.txt中

  

1,5,7,18,9,8,12
  2,41,12,11,1,10

我尝试过的代码:

list1 = []
list2 = []
infile = open("data.txt","r")
line = infile.readline()
for line in infile:
    line = line.split(',')
    list1.append(float(line))
    line = infile.readline()
    list2.append(float(line))
    print(list1)
    print(list2)
print()

我想拥有的内容:

list1 = [1, 5, 7, 18, 9, 8, 12]
list2 = [2, 41, 12, 11, 1, 10]

如何修复我的代码?

3 个答案:

答案 0 :(得分:4)

您的代码中存在许多错误,因此我将发布更好的方法:

with open('data.txt', 'r') as file:
    list1 = [int(number) for number in file.readline().split(',')]
    list2 = [int(number) for number in file.readline().split(',')]

print(list1)
print(list2)

输出:

[1, 5, 7, 18, 9, 8, 12]
[2, 41, 12, 11, 1, 10]

您也可以在一行中完成:

list1, list2 = [[int(n) for n in line.split(',')] for line in open('data.txt').readlines()]

答案 1 :(得分:1)

list1=[]
list2=[]
f = open("inputfile.txt","r")
lines = f.readlines()
f.close()
list1 = [int(x) for x in lines[0].split(",")]
list2 = [int(x) for x in lines[1].split(",")]

print(list1)
print(list2)

<强>输出:

[1, 5, 7, 18, 9, 8, 12]
[2, 41, 12, 11, 1, 10]

答案 2 :(得分:0)

list1=[]
list2=[]
lines = []
infile = open("data.txt","r")
for line in infile :
    line = line.split(',')
    lines.append(line)
list1 = lines[0]
list2 = lines[1]

print (list1)
print (list2)