如何从包含整数列表的元组构建字典?

时间:2013-05-30 06:41:19

标签: python

到目前为止,我的代码从两个不同的csv文件中读取并打印出来:

import itertools

def Compare(file1, file2):
    with open(file1+'.txt', 'r') as f1:
        with open(file2+'.txt', 'r') as f2:
            for line in itertools.product(f1, f2):
                lines = [[int(col) for col  in row.split()] for row in line]
                print(lines),

输出如下:

[[1, 2130, 164, 279, 90, 92, 193, 1], [1, 186, 164, 61, 110, 50, 74, 1]]

我想从两个列表中获取这些int值并将它们放在单独的词典中,其中一个键有5个不同的值,所以例如:

dict1={'key':'value1''value2''value3''value4''value5', 'key2:...etc}
dict2={'key':'value1''value2''value3''value4''value5', 'key2:...etc}

dict1是元组的[0],而dict2[1]。 值1-5是元组的每个列表中的值,因此dict1将保留values[0][0:4]作为示例。

我希望结果如下:

dict={164:[1,279,90,92,193]}

1 个答案:

答案 0 :(得分:1)

import itertools

def Compare(file1, file2):
    with open(file1+'.txt', 'r') as f1, open(file2+'.txt', 'r') as f2:
        for line in itertools.product(f1, f2): # line equals tuple of (f1[0],f2[0]), (f1[0], f2[1]), etc.
          # lines = [[int(col) for col  in row.split()] for row in line]
          # the tuple only contains 2 elements; first element should go to dict1, second to dict2. Why worry about that with list comprehensions?
          dict1 = {'key': [int(col) for col in line[0].split() ]}
          dict2 = {'key': [int(col) for col in line[1].split() ]}
          print(dict1, dict2)

除外:您使用的密钥是什么?您在每个文件的每行中引用5个值;但你有8个。