列表理解从字典中提取元组列表

时间:2011-03-20 23:20:06

标签: python list list-comprehension tuples

我想在下面的列表中使用list comprehension;

movie_dicts = [{'title':'A Boy and His Dog', 'year':1975, 'rating':6.6},
           {'title':'Ran', 'year':1985, 'rating': 8.3},
           {'title':'True Grit', 'year':2010, 'rating':8.0},
           {'title':'Scanners', 'year':1981, 'rating': 6.7}]

利用我对列表理解和词典的了解,我知道

movie_titles = [x['title'] for x in movie_dicts]
print movie_titles

将打印包含电影标题的列表。

为了提取我尝试过的(标题,年份)元组列表 -

movie_tuples = [x for ('title','year') in movie_dicts]
print movie_tuples

我收到错误SyntaxError:无法分配给文字

我不确定如何使用列表推导来获取两个(特定的)键/值对(这样做会自动生成一个元组?)

4 个答案:

答案 0 :(得分:23)

movie_dicts = [
    {'title':'A Boy and His Dog', 'year':1975, 'rating':6.6},
    {'title':'Ran', 'year':1985, 'rating': 8.3},
    {'title':'True Grit', 'year':2010, 'rating':8.0},
    {'title':'Scanners', 'year':1981, 'rating': 6.7}
]

title_year = [(i['title'],i['year']) for i in movie_dicts]

给出

[('A Boy and His Dog', 1975),
 ('Ran', 1985),
 ('True Grit', 2010),
 ('Scanners', 1981)]

OR

import operator
fields = operator.itemgetter('title','year')
title_year = [fields(i) for i in movie_dicts]

给出完全相同的结果。

答案 1 :(得分:3)

此版本至少可以重复:

>>> fields = "title year".split()
>>> movie_tuples = [tuple(map(d.get,fields)) for d in movie_dicts]

答案 2 :(得分:2)

[(movie_dict['title'], movie_dict['year']) for movie_dict in movie_dicts]

请记住,xs = [expr for target in expr2]相当于(为了简单而几乎忽略StopIteration):

xs = []
for target in expr2:
    xs.append(expr)

所以target需要是一个普通的旧变量名或一个要解包的元组。但由于movie_dicts不包含要解包的序列,而是简单的单个值(dicts),因此必须将其限制为一个变量。然后,当您追加到生成的列表时,您可以创建一个元组并执行您想要对当前项执行的任何操作。

答案 3 :(得分:0)

如果您不必使用列表推导,您可以随时执行:

list(d.iteritems())