2011-03-22 57 views
2

的結果,爲什麼我不能做這樣的事情:Python的 - 遍歷list.append

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

我認爲你已經'輸入'的'os'?但請注意:這是一個列表理解...不是生成器表達式。 – Johnsyweb 2011-03-22 11:30:24

+1

是什麼讓你覺得'append()'返回一個值?你在哪裏讀過的?你從哪裏看到過這樣的例子? – 2011-03-22 14:37:21

回答

10

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)] 
+1

這是一個我完全忘記的事實 – 2011-03-22 11:26:08

+1

@Martin:不用擔心,我們都忘記了事情。這就是爲什麼在編寫長期理解之前總是最好在交互式提示中編寫短代碼示例 – 2011-03-22 11:30:37

4

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

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