Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用nop的Python2.7列表操作_Python_Python 2.7_List - Fatal编程技术网

使用nop的Python2.7列表操作

使用nop的Python2.7列表操作,python,python-2.7,list,Python,Python 2.7,List,我想根据条件将一些数据附加到列表中: 这里,如果条件为false,当我希望arr仅包含abc时,我应该如何处理NOP?只需在另一行中执行即可: arr = ['abc'] if condition: arr.append('def') 也可以使用嵌套条件生成器: >>> ['abc', *(x for x in ['def'] if True), 'ghi'] ['abc', 'def', 'ghi'] >>> ['abc', *(x for x i

我想根据条件将一些数据附加到列表中:


这里,如果条件为false,当我希望arr仅包含abc时,我应该如何处理NOP?

只需在另一行中执行即可:

arr = ['abc']
if condition:
    arr.append('def')

也可以使用嵌套条件生成器:

>>> ['abc', *(x for x in ['def'] if True), 'ghi']
['abc', 'def', 'ghi']
>>> ['abc', *(x for x in ['def'] if False), 'ghi']
['abc', 'ghi']

不过,不确定那是否更干净;如果有更多的元素,可能是这样。

是否可以在列表操作中添加if语句?为什么要这样做?有理由这么做吗?在python中有很多方法可以做同样的事情,但只有少数方法是明确的。仔细检查,问题被标记为Python2.7,但这还不适用于它。。。
arr = ['abc'] + (['def'] if condition else [])
>>> ['abc', *(x for x in ['def'] if True), 'ghi']
['abc', 'def', 'ghi']
>>> ['abc', *(x for x in ['def'] if False), 'ghi']
['abc', 'ghi']