![](/img/trans.png)
[英]Create dictionary where keys are from a list and values are the sum of corresponding elements in another list
[英]How do I generate a dictionary using elements of a list as keys and their corresponding digits from a matrix as values?
所以我有一个清单
列表 = ['a','b','c','d','e','f','g']
和一个矩阵文件 in.txt
- 12 15 16 13
- b 9 83 24 72
- c 4 52 17 93
- 12 84 33 80
- 29 25 33 47
- 女 82 11 18 9
- 克 12 21 93 77
我应该如何编写代码,使我的字典键是列表的元素,值是矩阵文件中的数字? 例如
字典 = {'a':[12,15,16,13],'b':[9,83,24,72].....}
你可以做这样的事情
d = {}
with open('t.txt') as f:
for i in f:
l = i.split()
d[l[0]] = l[1::]
In [7]: d
Out[7]:
{'a': ['12', '15', '16', '13'],
'b': ['9', '83', '24', '72'],
'c': ['4', '52', '17', '93'],
'd': ['12', '84', '33', '80'],
'e': ['29', '25', '33', '47'],
'f': ['82', '11', '18', '9'],
'g': ['12', '21', '93', '77']}
使用 int 值更改行更新为d[l[0]] = list(map(int, l[1::]))
with open('t.txt') as f:
for i in f:
l = i.split()
print(l)
d[l[0]] = list(map(int, l[1::]))
output
Out[18]:
{'a': [12, 15, 16, 13],
'b': [9, 83, 24, 72],
'c': [4, 52, 17, 93],
'd': [12, 84, 33, 80],
'e': [29, 25, 33, 47],
'f': [82, 11, 18, 9],
'g': [12, 21, 93, 77]}
dict = {}
with open('file.txt', 'r') as f:
for line in f:
w = line.split() # w is a list of strings in the current line
dict[l[0]] = [int(w[i]) for i in range(1, len(w))]
print(dict)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.