从python

时间:2016-10-17 14:54:29

标签: python python-2.7 python-3.x

我可以知道文件中的数据如何分成两个单独的列表。例如, 文件包含数据为1,2,3,4; 5,6,7

my code:

for num in open('filename','r'):
  list1 = num.strip(';').split()

在这里,我想在半冒号(即[1,2,3,4]之前的新列表和半冒号之后的新列表(即)[5,6,7]

3 个答案:

答案 0 :(得分:2)

如果您确定您的文件只包含2个列表,则可以使用列表解析:

l1, l2 = [sub.split(',') for sub in data.split(';')]
# l1 = ['1', '2', '3', '4']
# l2 = ['5', '6', '7']

更一般地说,

lists = [sub.split(',') for sub in data.split(';')]
# lists[0] = ['1', '2', '3', '4']
# lists[1] = ['5', '6', '7']

如果需要整数,您可以使用第二个列表理解:

lists = [[int(item) for item in sub.split(',')] for sub in data.split(';')]

答案 1 :(得分:1)

要获得最终列表,您需要在","上进行拆分(可能map()结果为int()):

with open("filename") as f: 
     for line in f:
         list1, list2 = [x.split(",") for x in line.rstrip().split(";")]

答案 2 :(得分:0)

根据文件的大小,您可以简单地将整个文件一次性读取为字符串,然后先用分号分隔,然后用逗号分隔:

with open('filename', 'r') as f:  #open file
    s = f.read()   #read entire contents into string
    lists = s.split(';')  #split separate lists by semicolon delimiters
    for l in lists:  #for each list
        l = [int(x) for x in l.split(',')]  #separate the string by commas and convert to integers