如何使用列表中的元素作为键,将矩阵中相应的数字作为值来生成字典?

2024-04-25 09:44:28 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个清单

List = ['a','b','c','d','e','f','g']

和一个.txt格式的矩阵文件

  • 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

我应该如何编写代码,使我的字典键是列表的元素,值是矩阵文件中的数字? e、 g

dictionary = {'a':[12,15,16,13],'b':[9,83,24,72].....}


2条回答

你可以这样做

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::])) 


输出

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)

相关问题 更多 >

    热门问题