简体   繁体   English

我如何从容纳整数列表的元组中构建字典?

[英]How do i build a dictionary out of a tuple that holds lists of integers?

My code so far reads from two different csv files and prints them: 到目前为止,我的代码从两个不同的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),

The output looks like this: 输出看起来像这样:

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

I want to take those int values from the two lists and place them in seperate dictionaries where one key has 5 different values so for an example: 我想从两个列表中获取这些int值,并将它们放在单独的字典中,其中一个键具有5个不同的值,因此举一个例子:

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

Where dict1 is the [0] of the tuple and dict2 is [1] . 其中dict1是元组的[0] ,而dict2[1] And the values1-5 are values from each list of the tuple so dict1 would hold values[0][0:4] for an example. 并且值1-5是来自每个元组列表的值,因此dict1将保存values[0][0:4]

I want the outcome to look like this: 我希望结果看起来像这样:

dict={164:[1,279,90,92,193]}
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)

Except: What is the key you are using? 例外:您使用的密钥是什么? You refer to 5 values in each line in each file; 您在每个文件的每一行中引用5个值; but you have 8. 但是你有8。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM