2

我是 python 新手,我正在尝试使用元组作为键和嵌套列表作为多个值来制作字典。

该列表嵌套在三元组中;[[[Isolation source],[host],[country]]...etc]

下面的例子:

value_list = [[['NaN'], ['sponge'], ['Palau']], [['skin'], ['fish'], ['Cuba']], [['claw'], ['crab'], ['Japan: Aomori, Natsudomari peninsula']]....]

和键元组;

key_tuple = ('AB479448', 'AB479449', 'AB602436',...)

因此,我希望输出看起来像这样;

dict = {'AB479448': [NaN, sponge, Palau], 'AB479449': [skin, fish, Cuba], 'AB602436': [claw, crab, Japan: Aomori, Natsudomari peninsula]

我尝试了一些不同的解决方案,但我无法做到……例如字典理解;

dict = { i: value_list for i in key_tuple }

以上给了我这个(使用不同的键,但将相同的值关联到每个键);

{'AB479448': [[[NaN, sponge, Palau]]], 'AB479449': [[[NaN, sponge, Palau]]], 'AB602436': [[[NaN, sponge, Palau]]]...etc..}

将不胜感激任何指针...谢谢!

4

3 回答 3

7

您可以使用itertools.chain.from_iterable, itertools.izip(or zip) 和 dict 理解:

>>> from itertools import chain, izip
>>> value_list = [[['NaN'], ['sponge'], ['Palau']], [['skin'], ['fish'], ['Cuba']], [['claw'], ['crab'], ['Japan: Aomori, Natsudomari peninsula']]]
>>> key_tuple = ('AB479448', 'AB479449', 'AB602436')
>>> {k: list(chain.from_iterable(v)) for k, v in izip(key_tuple, value_list)}
{'AB479449': ['skin', 'fish', 'Cuba'],
 'AB479448': ['NaN', 'sponge', 'Palau'],
 'AB602436': ['claw', 'crab', 'Japan: Aomori, Natsudomari peninsula']}
于 2013-10-30T07:18:23.790 回答
1

使用zipiter您可以创建所需的输出字典,如下所示

value_list = [[['NaN'], ['sponge'], ['Palau']], [['skin'], ['fish'], ['Cuba']], [['claw'], ['crab'], ['Japan: Aomori, Natsudomari peninsula']]]
key_tuple = ('AB479448', 'AB479449', 'AB602436')

dict( (key,[[list(value)]]) for key,value in zip(key_tuple, zip(*(iter(t[0] for v in value_list for t in v),)*3)))

Out[16]: {'AB479448': [[['NaN', 'sponge', 'Palau']]], 'AB479449': [[['skin', 'fish', 'Cuba']]],'AB602436': [[['claw', 'crab', 'Japan: Aomori, Natsudomari peninsula']]]}

如果列表键中所需的元素数量发生变化,您可以替换3新的长度值。


做这个真的很有趣。

于 2013-10-30T07:28:31.673 回答
1

这是使用itertools.chain.from_iterable和字典理解的解决方案:

from itertools import chain
{keys[i]:list(chain.from_iterable(contents)) for i, contents in enumerate(my_list)}

这等于:

from itertools import chain
for i, contents in enumerate(my_list): #get [['skin'], ['fish'], ['Cuba']]
    result[keys[i]] = list(chain.from_iterable(contents))

演示

>>> from itertools import chain
>>> my_list = [[['NaN'], ['sponge'], ['Palau']], [['skin'], ['fish'], ['Cuba']], [['claw'], ['crab'], ['Japan: Aomori, Natsudomari peninsula']]]
>>> keys = ('AB479448', 'AB479449', 'AB602436')
>>> {keys[i]:list(chain.from_iterable(contents)) for i, contents in enumerate(my_list)}
{'AB479449': ['skin', 'fish', 'Cuba'], 'AB479448': ['NaN', 'sponge', 'Palau'], 'AB602436': ['claw', 'crab', 'Japan: Aomori, Natsudomari peninsula']}
>>> 

希望这可以帮助!

于 2013-10-30T07:32:41.310 回答