0

到目前为止,我的代码从两个不同的 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是。values1-5 是元组每个列表中的值,因此可以举个例子。[0]dict2[1]dict1values[0][0:4]

我希望结果如下所示:

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

1 回答 1

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 个。

于 2013-05-30T06:55:39.907 回答