可以在不同长度的iterable上使用列表推导吗?

Jub*_*les 0 python list-comprehension

是否可以通过列表解析创建列表,该列表解析使用复合布尔表达式,该表达式至少有一个条件假定存在来自底层迭代元素的索引值(即使另一个条件不存在且(应该?)导致表达是True)?

IndexError: tuple index out of range执行下面的代码时,解释器抛出.

my_lst = [('30', ), ('30', '125'), ('30', '127'), ('30', '125', '567')]
[tpl for tpl in my_lst if (len(tpl) == 1 or tpl[2] == '125')]
# Desired result: [('30', ), ('30', '125'), ('30', '125', '567')]
Run Code Online (Sandbox Code Playgroud)

iCo*_*dez 5

Python索引从0开始.索引2将检索第三个项目,而不是第二项目.

您想要访问索引1(第二项):

[tpl for tpl in my_lst if (len(tpl) == 1 or tpl[1] == '125')]
Run Code Online (Sandbox Code Playgroud)