字典中具有多个值的键(Python)

2024-04-23 23:42:22 发布

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

我有以下列表(我从列表中省略了一些值):

all_examples=   ['A,1,1', 'B,2,1', 'C,4,4', 'D,4,5',...]

我需要创建一个字典,使一个键有多个值。你知道吗

dict = {"A":[1,1], "B":[2,1]}

我找了一些可能的解决办法,但没能使我的解决办法奏效。你知道吗


Tags: 列表字典allexamplesdict省略解决办法奏效
3条回答

简单而直接的解决方案:

result = {}
for l in all_examples:
    split_list = l.split(',')
    result[split_list[0]] = [int(val) for val in split_list[1:]]

一个简短但效率不高的解决方案

all_examples = ['A,1,1', 'B,2,1', 'C,4,4', 'D,4,5']
d = dict((a.split(',')[0], a.split(',')[1:])for a in all_examples)

对于python3,您可以使用dict comp,使用extended iterable unpacking拆分列表中的每个字符串,并从拆分的元素中创建一个键/值:

l = ['A,1,1', 'B,2,1', 'C,4,4', 'D,4,5']

d = {k: list(map(int,rest)) for k,*rest in (s.split(",") for s in l) }

对于python2,语法并没有那么好:

l = ['A,1,1', 'B,2,1', 'C,4,4', 'D,4,5']

d = {s[0]: map(int, s[1:] ) for s in (s.split(",") for s in l)}

两者都应该给你一些类似的东西:

In [32]:  d = {k: list(map(int,rest)) for k,*rest in (s.split(",") for s in l) } 
In [33]: d
Out[33]: {'A': [1, 1], 'B': [2, 1], 'C': [4, 4], 'D': [4, 5]}

为了分解它,内部gen exp正在创建拆分字符串:

In [35]: list (s.split(",") for s in l)
Out[35]: [['A', '1', '1'], ['B', '2', '1'], ['C', '4', '4'], ['D', '4', '5']]

在python3的情况下,for k,*rest in..k是列表的第一个元素,*rest语法基本上意味着其他一切。你知道吗

 In [37]: for k,*rest in (s.split(",") for s in l):
              print(k, rest)
   ....:     
A ['1', '1']
B ['2', '1']
C ['4', '4']
D ['4', '5']

因此,将所有这些放在一起使用for循环创建dict将是:

In [38]: d = {}

In [39]: for k,*rest in (s.split(",") for s in l):
              d[k] = list(map(int, rest))
   ....:     

In [40]: d
Out[40]: {'A': [1, 1], 'B': [2, 1], 'C': [4, 4], 'D': [4, 5]}

或者对于Python2:

In [42]: d = {}

In [43]: for spl in (s.split(",") for s in l):
              d[spl[0]] = list(map(int,spl[1:]))
   ....:     

In [44]: d
Out[44]: {'A': [1, 1], 'B': [2, 1], 'C': [4, 4], 'D': [4, 5]}

相关问题 更多 >