1
['*a*', '*b*', '*c*', '*d*', '*f*','*g*']
['11', '22', '33', '44', '', '55']
['66', '77', '88', '', '99', '10']
['23', '24', 'sac', 'cfg', 'dfg', '']

需要输入字典为:

{a : ('11','66','23'),b : ('22','77','24'),c : ('33','88','sac'),d :('44','','cfg')}

这些行是从 CSV 文件中读取的:

import csv
csvFile = csv.reader(open("sach.csv", "rb"))
for row in csvFile:
    print row

上面显示的代码,上面显示了行的输出,其中有很多列表。请帮我把它放在字典格式中,如上所示。

4

1 回答 1

7

压缩行:

with open("sach.csv", "rb") as csv_infile:
    reader = csv.reader(csv_infile)
    yourdict = {r[0].replace('*', ''): r[1:] for r in zip(*reader)}

zip()函数为您进行配对,通过传入reader带有*参数的对象 Python 将遍历 CSV 行并将每一行作为单独的参数传递给zip().

于 2013-07-17T14:43:40.713 回答