一个变量中的多个主列表

时间:2015-02-23 19:50:38

标签: python python-3.x

我试图解决这个问题...我有csv文件,其中包含:

jmeno,prijmeni,roknarozeni
"adam","novak",1995
"petr","papousek",1992
"josef","petrklic",1985

我的努力:

import re
for line in open('C:\\Users\\Vlada\\Desktop\\SKOLA\\WVA\\csv.csv'):
  line = line.replace('"','')
  line = re.split('\W+', line)
  print (line) 

但输出是:

['jmeno', 'prijmeni', 'roknarozeni', '']
['adam', 'novak', '1995', '']
['petr', 'papousek', '1992', '']
['josef', 'petrklic', '1985', '']

而不是:

[['jmeno', 'prijmeni', 'roknarozeni', '']
['adam', 'novak', '1995', '']
['petr', 'papousek', '1992', '']
['josef', 'petrklic', '1985', '']]

1 个答案:

答案 0 :(得分:0)

根本不需要re。剥离"并拆分,,如果你想要一个列表列表,然后附加到一个列表:

out = []
with open('C:\\Users\\Vlada\\Desktop\\SKOLA\\WVA\\csv.csv') as f:
    for line in f:
        out.append([x.strip('"') for x in line.rstrip().split(",")])

[['jmeno', 'prijmeni', 'roknarozeni'], ['adam', 'novak', '1995'], ['petr', 'papousek', '1992'], ['josef', 'petrklic', '1985']]

或者替换和列表理解:

with open('C:\\Users\\Vlada\\Desktop\\SKOLA\\WVA\\csv.csv') as f:
    print([line.replace('"',"").rstrip().split(",") for line in f])

[['jmeno', 'prijmeni', 'roknarozeni'], ['adam', 'novak', '1995'], ['petr', 'papousek', '1992'], ['josef', 'petrklic', '1985']]

我认为你实际上想要列表中的空字符串。