列表理解从字典中提取元组列表
我想在以下列表中使用列表理解;
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: can't allocate toliteral
我不确定如何使用列表获取两个(特定)键/值对理解(这样做会自动生成一个元组?)
I'd like to use list comprehension on the following list;
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}]
using my knowledge of list comprehension and dictionaries, I know that
movie_titles = [x['title'] for x in movie_dicts]
print movie_titles
will print a list with movie titles.
In order to extracts a list of (title, year) tuples I've tried -
movie_tuples = [x for ('title','year') in movie_dicts]
print movie_tuples
and I receive the error SyntaxError: can't assign to literal
I'm unsure on how to fetch the two (specific) key/value pairs using list comprehension (doing so would generate a tuple automatically?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
给出
OR
给出完全相同的结果。
gives
OR
which gives exactly the same result.
这个版本至少有重复:
This version has a minimum of repeating yourself:
请记住,
xs = [expr for target in expr2]
等效于(为了简单起见,几乎忽略了StopIteration
):因此
target
需要是普通的旧变量名称或一些要解压到的元组。但由于 movie_dicts 不包含要解压的序列,而是简单的单个值(字典),因此您必须将其限制为一个变量。然后,当您追加到正在生成的列表时,您可以创建一个元组并对当前项目执行您想要执行的任何其他操作。Remember,
xs = [expr for target in expr2]
is equivalent (almost - ignoringStopIteration
for simplicity) to:So
target
needs to be a plain old variable name or some tuple to unpack to. But sincemovie_dicts
doesn't contain sequences to unpack from but simple single values (dicts), you must limit it to one variable. Then when you append to the list being generated, you can create a tuple and do whatever else you want to do with the current item.如果您不必使用列表理解,您始终可以这样做:
If you don't have to use a list comprehension, you could always do: