Python - 从列表中创建元组

时间:2016-11-08 01:56:53

标签: python list dictionary tuples list-comprehension

给出dictionary

sql_playlists={
'user1':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 1': 1.0},
'user2':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 2': 1.0},
'user3':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 3': 1.0},
'user4':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 4': 1.0},
'user5':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 4': 1.0}}

我可以像这样创建keysvalues的数据元组:

sqltuples = [(k1,k2,v2) for k1,v1 in sql_playlists.items()
             for k2,v2 in v1.items()]

输出:

[(u'user1', u'Make You Feel My Love', 1.0), (u'user1', u'I See Fire', 1.0), (u'user', u'High And Dry', 1.0), (u'user1', u'Fake Plastic Trees', 1.0), (u'user1', u'One', 1.0), (u'user1', u'Goodbye My Lover', 1.0), (u'user1', u'No Surprises', 1.0)]

为每个用户。

但是如果sql_playlistlist,相同的数据结构但在[]内,而不是dictionary会怎样?

编辑:列表

sql_playlists=[{
'user1':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 1': 1.0},
'user2':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 2': 1.0},
'user3':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 3': 1.0},
'user4':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 4': 1.0},
'user5':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 4': 1.0}}]

如何调整list comprehension以便从列表中生成相同的tuples

这适用于第一个用户:

sqltuples = [(k1,k2,v2) for k1,v1 in sql_playlists[0].items()
             for k2,v2 in v1.items()]

但我想要所有用户。

1 个答案:

答案 0 :(得分:0)

如果你的意思是字典数组: sql_playlists=[ {'user1':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 1': 1.0}}, {'user2':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 2': 1.0}}, {'user3':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 3': 1.0}}, {'user4':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 4': 1.0}}, {'user5':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 4': 1.0}}]

然后:

sqltuples = [(k1,k2,v2) for vlist in sql_playlists for k1,v1 in vlist.items() for k2,v2 in v1.items()]

你应该注意,这将以不同的顺序产生元组,因为在枚举列表而不是dicts时保留了排序