2013-06-04 66 views
2

任何想法,爲什麼當我打電話:通過索引替換python列表中的項目..失敗?

>>> hi = [1, 2] 
>>> hi[1]=3 
>>> print hi 
[1, 3] 

我可以通過它的索引更新列表項,但是當我打電話:

>>> phrase = "hello" 
>>> for item in "123": 
>>>  list(phrase)[int(item)] = list(phrase)[int(item)].upper() 
>>> print phrase 
hello 

它失敗了呢?

應該hELLo

回答

8

您還沒有初始化phrase(該list你打算做)到一個變量呢。所以幾乎你在每個循環中都創建了一個列表,它完全一樣。

如果您打算實際更改phrase的字符,那麼這是不可能的,就像在Python中一樣,字符串是不可變的。

也許可以製作phraselist = list(phrase),然後編輯for循環中的列表。如果你喜歡一個班輪

>>> phrase = "hello" 
>>> phraselist = list(phrase) 
>>> for i in range(1,4): 
...  phraselist[i] = phraselist[i].upper() 
... 
>>> print ''.join(phraselist) 
hELLo 
+0

好的回答:) +1 –

+0

@InbarRose謝謝:)。 – TerryA

3
>>> phrase = "hello" 
>>> list_phrase = list(phrase) 
>>> for index in (1, 2, 3): 
     list_phrase[index] = phrase[index].upper() 
>>> ''.join(list_phrase) 
'hELLo' 

>>> ''.join(x.upper() if index in (1, 2, 3) else x for 
      index, x in enumerate(phrase)) 
'hELLo' 
+0

還有一個沒用的'list(phrase)' – jamylak

+0

@jamylak謝謝。從OP代碼複製粘貼剩餘。刪除。 –

0

認爲字符串是不可變的python不能修改現有的字符串可以創建新此外,您還可以使用range()

''.join([c if i not in (1, 2, 3) else c.upper() for i, c in enumerate(phrase)])

1

另一個答案,只是爲了好玩:)

phrase = 'hello' 
func = lambda x: x[1].upper() if str(x[0]) in '123' else x[1] 
print ''.join(map(func, enumerate(phrase))) 
# hELLo 

爲了使這一強大的,我創建了一個方法:(因爲我真棒,和無聊)

def method(phrase, indexes): 
    func = lambda x: x[1].upper() if str(x[0]) in indexes else x[1] 
    return ''.join(map(func, enumerate(phrase))) 

print method('hello', '123') 
# hELLo 
+1

因爲使用列表解析太主流了 – TerryA

+0

@Haidro你明白了......(什麼,沒有+1?):-) –

+0

嗯...我不知道...它看起來非常非pythonic ... – TerryA

0

list()創建一個新的列表。您的循環會在每次迭代中創建並立即丟棄兩個新列表。你可以把它寫成:

phrase = "hello" 
L = list(phrase) 
L[1:4] = phrase[1:4].upper() 
print("".join(L)) 

或無列表:

print("".join([phrase[:1], phrase[1:4].upper(), phrase[4:]])) 

字符串是不可變的Python因此去改變它,你需要創建一個新的字符串。

或者,如果你正在處理的字節串,你可以使用bytearray這是可變的:

phrase = bytearray(b"hello") 
phrase[1:4] = phrase[1:4].upper() 
print(phrase.decode()) 

如果指數不連續;你可以使用一個明確的for循環:

indexes = [1, 2, 4] 
for i in indexes: 
    L[i] = L[i].upper() 
相關問題