【问题标题】:Concise Way of Get Matching Element in List [duplicate]在列表中获取匹配元素的简洁方法[重复]
【发布时间】:2015-08-08 19:46:02
【问题描述】:

我有一个看起来像这样的列表

[{'name': 'red', 'test':4},... {'name': 'reded', 'test':44}]`

我有一个名字(例如:reded),我想在上面的列表中找到字典中将name 设置为reded 的字典。这样做的简洁方法是什么?

我的尝试看起来类似于

x = [dict_elem for dict_elem in list_above if dict_elem['name']==reded]

那我做

final_val = x[0]

如果名称匹配。这也可以通过for loop 来完成,但似乎有一个简单的单行代码可以做到这一点。我错过了什么吗?

【问题讨论】:

  • 好吧,您可以将第一行替换为第二行...[dict_elem for dict_elem in list_above if dict_elem['name']==reded][0]

标签: python


【解决方案1】:

你几乎在那里。如果您使用生成器而不是列表理解,则可以将其传递给next,它接受第一项。

try:
    x = next(dict_elem for dict_elem in list_above if dict_elem['name'] == reded)
except StopIteration:
    print "No match found"

或者

x = next((dict_elem for dict_elem in list_above if dict_elem['name'] == reded), None)
if not x:
    print "No match found"

【讨论】:

  • 西部最快的手指。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-27
  • 2011-12-02
  • 1970-01-01
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 2016-09-12
相关资源
最近更新 更多