【问题标题】:Python - iterating over result of list.appendPython - 迭代 list.append 的结果
【发布时间】:2011-03-22 11:18:41
【问题描述】:

为什么我不能这样做:

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

【问题讨论】:

  • 我想你已经 imported os?但请注意:这是一个列表推导......不是生成器表达式。
  • 是什么让您认为append() 返回值?你在哪里读的?你在哪里看到过这样的例子?

标签: python list


【解决方案1】:

list.append 在 Python 中不返回任何内容:

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

你可能想要这个:

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

或者,在您的代码中:

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

【讨论】:

  • 这是我完全忘记的事实
  • @Martin:别担心,我们都会忘记事情。这就是为什么在编写长推导之前最好在交互式提示中编写简短的代码示例
【解决方案2】:

如果您不想重复列表,也可以使用itertools.chain

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

【讨论】:

    猜你喜欢
    • 2020-01-02
    • 2015-04-08
    • 2023-02-01
    • 2018-07-11
    • 2011-12-12
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    • 2016-03-11
    相关资源
    最近更新 更多