python列表理解中的语法错误

ber*_*436 0 python

我有一个像这样的xlib元素列表:

<Choice ID="91149" Total="21"/>
<Choice ID="91139" Total="14"/>
<Choice ID="91159" Total="58"/>
Run Code Online (Sandbox Code Playgroud)

我想选择ID = 91149的元素.在.NET中,我可以做类似的事情

element91149 = (from p in choices where p.id=91149).first
Run Code Online (Sandbox Code Playgroud)

我正在尝试python中的语法,从python教程的这个例子开始......

#example from documentation = x for x in 'abracadabra' if x not in 'abc'
Run Code Online (Sandbox Code Playgroud)

我的实施:

h = x for x in results if x.get("ID")=="91149" #invalid syntax
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

iCo*_*dez 7

列表推导必须用方括号括起来[...]:

h = [x for x in results if x.get("ID")=="91149"]
Run Code Online (Sandbox Code Playgroud)

只是为了记录,使用普通括号(...)将创建一个生成器表达式:

h = (x for x in results if x.get("ID")=="91149")
Run Code Online (Sandbox Code Playgroud)

但是,正如@Ashwini所提到的,当你想要的只是符合条件的第一个项目时,将整个列表读入内存通常是非常低效的.

相反,使用它next和生成器表达式通常要快得多:

h = next(x for x in results if x.get("ID")=="91149")
Run Code Online (Sandbox Code Playgroud)

与列表comp不同.(一次完成所有操作),此解决方案将一次生成一个项目.而且,一旦找到符合条件的物品,它就会停止.

但要注意,StopIteration如果找不到该项,它也会引发错误.为避免这种情况,您可以提供next一个默认值来返回:

h = next((x for x in results if x.get("ID")=="91149"), None)
Run Code Online (Sandbox Code Playgroud)

在这种情况下,如果找不到符合条件的项目,h将分配给您None.