简体   繁体   English

python列表理解中的语法错误

[英]Bad syntax in python list comprehension

I have a list of xlib elements like this: 我有这样的xlib元素列表:

<Choice ID="91149" Total="21"/>
<Choice ID="91139" Total="14"/>
<Choice ID="91159" Total="58"/>

I want to pick the element with ID = 91149. In .NET, I could do something like 我想选择ID = 91149的元素。在.NET中,我可以做类似的事情

element91149 = (from p in choices where p.id=91149).first

I am trying at the syntax in python, working from this example from the python tutorial... 我想在Python中的语法,从工作这个例子从Python教程...

#example from documentation = x for x in 'abracadabra' if x not in 'abc'

My implementation: 我的实现:

h = x for x in results if x.get("ID")=="91149" #invalid syntax

What am I doing wrong? 我究竟做错了什么?

List comprehensions must be enclosed by square brackets [...] : 列表理解必须用方括号[...]括起来:

h = [x for x in results if x.get("ID")=="91149"]

Just for the record, using normal parenthesis (...) will create a generator expression : 仅作记录,使用普通括号(...)将创建一个生成器表达式

h = (x for x in results if x.get("ID")=="91149")

However, as @Ashwini mentioned, it is generally very inefficient to read a whole list into memory when all you want is the first item that meets a condition. 但是,正如@Ashwini所提到的,当您所需要的只是满足条件的第一项时,将整个列表读入内存通常效率很低。

Instead, it is usually much faster to use next and a generator expression: 相反,通常使用next和生成器表达式要快得多:

h = next(x for x in results if x.get("ID")=="91149")

Unlike the list comp. 与列表组合不同。 (which does it all at once), this solution will yield the items one at a time. (一次完成所有操作),此解决方案将一次生成一个项目。 Moreover, it will stop once it finds an item that meets the condition. 而且,一旦找到符合条件的物品,它将停止。

Be warned though that it will also raise a StopIteration error if it cannot find the item. 请注意,如果找不到该项目,也会引发StopIteration错误。 To avoid this, you can give next a default value to return: 为了避免这种情况,您可以给next一个默认值以返回:

h = next((x for x in results if x.get("ID")=="91149"), None)

In this case, h will be assigned to None if an item that meets the condition cannot be found. 在这种情况下,如果找不到满足条件的项目, h将被分配为None

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM