2013-05-13 45 views
-4

我必須在目錄中創建更多的文件,因此我希望這可以通過語法來完成。我所選擇的python但如何解決以下問題如何修改python 2.x中的列表項,使用循環

我有一個列表

L = [ 'A', 'B', 'C']

現在我要修改在列表L中的條目,如下

L = [ 'A.TXT', 'b.txt', 'c.txt']

如何做到這一點?

+6

請不要編輯您的問題,以現有的答案是無效的,而不是要求人們爲你編寫代碼,至少要顯示你迄今爲止所嘗試的內容(儘管公平,但爲你編寫代碼的4人可能會爲你寫更多內容,即使你根本沒有努力......) – geoffspear 2013-05-13 11:16:50

回答

2

修改列表,遍歷它使用指數:

for i in range(len(L))): 
    L[i] += '.txt' 

然而,在這種情況下,你並不真的需要修改的列表,所以你可能需要使用列表comrehension,作爲建議由@Ashwini喬杜裏。然而,使用列表理解創建名單,所以你可能會再次爲它分配到L:

L = [s + '.txt' for s in L] 

但是,如果原來的變量L是一個全球性的或非局部變量,上面的語句將創建新的本地變量,即會消失在當前功能的結束,如果你嘗試了asssignment之前訪問它可以創建一個爛攤子:

>>> L = ['a', 'b', 'c'] 
>>> def addtxt(): 
...  print(L) 
...  L = [s + '.txt' for s in L] 
... 
>>> addtxt() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 2, in addtxt 
UnboundLocalError: local variable 'L' referenced before assignment 

您將需要(在其他情況下或nonlocal)聲明添加global。這不是一個乾淨的方式來處理這個問題。

因此,就地置換列表理解相結合,你從@Jamylak

L[:] = [s + '.txt' for s in L] 

得到的建議,其中[:]意味着該列表的內容將被分配的右側被替換。這不會添加本地綁定,並將適合上述循環適合的任何位置。

3
>>> L=['a','b','c'] 
>>> L[:] = [x + '.txt' for x in L] 
>>> L 
['a.txt', 'b.txt', 'c.txt'] 

切片分配[:]用於突變L本身並保留引用。例如。這是,如果你不使用它

>>> L=['a','b','c'] 
>>> L2 = L # you may have a reference like this in your code somewhere 
>>> L = [x + '.txt' for x in L] # this simply reassigns the name L to a new value 
>>> L 
['a.txt', 'b.txt', 'c.txt'] 
>>> L2 # but doesn't affect the name L2 which is still binded to the old list 
['a', 'b', 'c'] 
+0

+1,用於'L [:]',它的更清潔。 – 2013-05-13 11:18:26

2

比以前的簡單答案一點點發生了什麼:

L = [i + '.txt' for i in L] 

for i, string in enumerate(L): 
    L[i] = string + '.txt' 
+0

第一個選項在語義上不等同於第二個選項。第二種方法的缺點是用'string'混淆了'L [i]',這使它有點混亂。我認爲'+ ='更好。 – Elazar 2013-05-13 23:48:04