python - 使用 else pass 的列表理解

标签 python python-2.7 list-comprehension

如何在列表理解中执行以下操作?

test = [["abc", 1],["bca",2]]

result = []
for x in test:
    if x[0] =='abc':
        result.append(x)
    else:
        pass
result
Out[125]: [['abc', 1]]

尝试 1:

[x if (x[0] == 'abc') else pass for x in test]
  File "<ipython-input-127-d0bbe1907880>", line 1
    [x if (x[0] == 'abc') else pass for x in test]
                                  ^
SyntaxError: invalid syntax

尝试 2:

[x if (x[0] == 'abc') else None for x in test]
Out[126]: [['abc', 1], None]

尝试 3:

[x if (x[0] == 'abc') for x in test]
  File "<ipython-input-122-a114a293661f>", line 1
    [x if (x[0] == 'abc') for x in test]
                            ^
SyntaxError: invalid syntax

最佳答案

if 需要放在最后,您不需要在列表理解中使用 pass。仅当满足 if 条件时才会添加该项目,否则将忽略该元素,因此 pass 在列表理解语法中隐式实现。

[x for x in test if x[0] == 'abc']

为了完整起见,此语句的输出为:

[['abc', 1]]

关于python - 使用 else pass 的列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33691552/

相关文章:

python - Travis 脚本退出代码永远不会失败,即使应该失败

python - 无法让 Scrapy 解析并遵循 301、302 重定向

python - 使用 Pycharm 编写 gem5 配置脚本

python - 检查嵌套迭代中的所有元素是否都评估为 False

python - 使用列表理解更改列表中的多个元素

python - if-else 理解字典在 python3 中不起作用

linux - python : using function

python - 如何比较 strftime 值

python - 修剪 python bs4 中的空格

sql - 如何在 R 数据帧上执行类似 SQL 的操作?