【问题标题】:merge a key which is tuple type with a value which is a list of tuple in one list of tuples, python [closed]将元组类型的键与一个元组列表中的元组列表值合并,python [关闭]
【发布时间】:2018-08-24 19:14:34
【问题描述】:

我想用元组键和列表值更改字典以根据我们拥有的键的数量列出一个或多个列表

示例: 如您所见,键中的元组和值中的元组列表。

input 
f = {('justin', '0'): [('fun', '1'), ('crazy', '2')],
 ('julie', '3'): [('fun', '4'), ('crazy', '5')]}

desired output1: 

f = [('justin', '0'),('fun', '1'), ('crazy', '2')],[('julie', '3'),('fun', '4'), ('crazy', '5')]

desired output1: 

 f = [('justin', '0'),('fun', '1'), ('crazy', '2'),('julie', '3'),('fun', '4'), ('crazy', '5')]

【问题讨论】:

  • 试试这个:result = list([key] + [v for v in value] for key,value in f.items())。它会给你第一个想要的输出。

标签: python list dictionary tuples iteration


【解决方案1】:

您可以为您想要的第一个输出连接键值对,然后展平以实现第二个:

f = {('justin', '0'): [('fun', '1'), ('crazy', '2')], ('julie', '3'): [('fun', '4'), ('crazy', '5')]}
desired_1 = [[a]+b for a, b in f.items()]
desired_2 = [i for b in desired_1 for i in b]

输出:

[[('justin', '0'), ('fun', '1'), ('crazy', '2')], [('julie', '3'), ('fun', '4'), ('crazy', '5')]]
[('justin', '0'), ('fun', '1'), ('crazy', '2'), ('julie', '3'), ('fun', '4'), ('crazy', '5')]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 2015-10-30
    • 2013-09-01
    • 2013-09-25
    • 2022-06-15
    • 2016-12-19
    • 1970-01-01
    相关资源
    最近更新 更多