将列表项追加到字典,Python

时间:2019-07-12 15:07:28

标签: python python-3.x

我有一个包含以下项目的列表

print(List)
['x, y, z', '1, 2, 3', '2, 4, 6', '4, 8, 12']

和一个包含三个空列表的字典

print(Dictionary)
{0: [], 1: [], 2: []}

现在我想将每个项目拆分为单独的列表

print(List1)
['x', 'y', 'z']

print(List2)
['1', '2', '3']

and so forth..

,然后将新列表中的每个项目附加到字典中,以便

print(Dictionary)
{0: ['x', '1', '2', '4'], 1: ['y', '2', '4', '8'], 2: ['z', '3', '6', '12']} 

5 个答案:

答案 0 :(得分:0)

  1. lists中的str中获取列表。我删除空间并用,分割。
  2. 我使用key中的dictionaries作为每个列表的索引。
lists = ['x, y, z', '1, 2, 3', '2, 4, 6', '4, 8, 12']
dictionaries = {0: [], 1: [], 2: []}

lists = [x.replace(' ', '').split(',') for x in lists]
for key in dictionaries.keys():
    dictionaries[key] = [x[key] for x in lists]

print (dictionaries)

结果是:

{0: ['x', '1', '2', '4'], 1: ['y', '2', '4', '8'], 2: ['z', '3', '6', '12']}

答案 1 :(得分:0)

借助itertools

l = ['x, y, z', '1, 2, 3', '2, 4, 6', '4, 8, 12']
d = {0: [], 1: [], 2: []}

from itertools import chain

for idx, val in zip(sorted(d.keys()), zip(*chain.from_iterable([v.split(', ')] for v in l))):
    d[idx].extend(val)

print(d)

打印:

{0: ['x', '1', '2', '4'], 1: ['y', '2', '4', '8'], 2: ['z', '3', '6', '12']}

答案 2 :(得分:0)

这是一个快速解决方案

lst = ['x, y, z', '1, 2, 3', '2, 4, 6', '4, 8, 12']
dct = {0: [], 1: [], 2: []}

letters = lst[0].split(', ')

for key in dct:
  numbers = lst[key + 1].split(', ')

  dct[key].append(letters[key])
  dct[key].extend(numbers)

print(dct)

答案 3 :(得分:0)

这是单发方式

import re

def dictChunker(content):
    chunker = {}
    for element in content:
        splittedElements = re.findall(r'\w+', element)
        for i in range(len(splittedElements)):
            chunker.setdefault(i, []).append(splittedElements[i])
    return chunker
>>> L = ['x, y, z', '1, 2, 3', '2, 4, 6', '4, 8, 12']
>>> dictChunker(L)
{0: ['x', '1', '2', '4'], 1: ['y', '2', '4', '8'], 2: ['z', '3', '6', '12']}

答案 4 :(得分:0)

这是一个使用列表/字典理解和zip()的班轮:

lst= ['x, y, z', '1, 2, 3', '2, 4, 6', '4, 8, 12']

dct = { i:v for i,v in enumerate(zip(*(s.split(", ") for s in lst))) }

# {0: ['x', '1', '2', '4'], 1: ['y', '2', '4', '8'], 2: ['z', '3', '6', '12']}

如果您不介意元组而不是字典值列表:

dct = dict(enumerate(zip(*(s.split(", ") for s in lst))))

# {0: ('x', '1', '2', '4'), 1: ('y', '2', '4', '8'), 2: ('z', '3', '6', '12')}