【发布时间】:2022-01-12 11:11:57
【问题描述】:
dictionary = {1: ['a', 'b'], 2: ['a'], 3: ['b', 'c']}
我希望这本字典在这样的元组列表中: 输出:
[(1, 'a'),(1, 'b'),(2, 'a'),(3, 'b'),(3, 'c')]
请帮帮我!!!
【问题讨论】:
标签: python list dictionary tuples
dictionary = {1: ['a', 'b'], 2: ['a'], 3: ['b', 'c']}
我希望这本字典在这样的元组列表中: 输出:
[(1, 'a'),(1, 'b'),(2, 'a'),(3, 'b'),(3, 'c')]
请帮帮我!!!
【问题讨论】:
标签: python list dictionary tuples
你可以通过理解来做到这一点:
[(x, z) for x, y in dictionary.items() for z in y]
或展开:
out = []
for x, y in dictionary.items():
for z in y:
out.append((x, z))
【讨论】:
字典 = {1: ['a', 'b'], 2: ['a'], 3: ['b', 'c']}
list_of_tuples = []
for k,v_list in dictionary.items():
for v in v_list:
list_of_tuples.append((k,v))
list_of_tuples
【讨论】: