简体   繁体   English

Python - 迭代list.append的结果

[英]Python - iterating over result of list.append

为什么我不能这样做:

files = [file for file in ['default.txt'].append(sys.argv[1:]) if os.path.exists(file)]

list.append doesn't return anything in Python: list.append不会在Python中返回任何内容:

>>> l = [1, 2, 3]
>>> k = l.append(5)
>>> k
>>> k is None
True

You may want this instead: 你可能想要这个:

>>> k = [1, 2, 3] + [5]
>>> k
[1, 2, 3, 5]
>>> 

Or, in your code: 或者,在您的代码中:

files = [file for file in ['default.txt'] + sys.argv[1:] if os.path.exists(file)]

You could also use itertools.chain if you don't want to duplicate lists. 如果您不想复制列表,也可以使用itertools.chain

files = [file for file in itertools.chain(['default.txt'], sys.argv[1:])
                  if os.path.exists(file)]

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

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