![](/img/trans.png)
[英]Why can't I manipulate a list items using for in loop? (Python)
[英]Why can't I change items in a Python list using a step?
因此,我仍處於學習Python的初期階段,並為此進行整體編碼。
我的問題是為什么我不能使用以下步驟更改Python列表中的項目:
def myfunc2(string):
new = list(string)
new[0::2] = new[0::2].upper()
new[1::2] = new[1::2].lower()
return '' .join(new)
myfunc2('HelloWorld')
我想使其他所有字母都大寫和小寫,從索引0開始。
我已經看到了另一個用戶發布的解決方案,盡管這個其他解決方案有效,但是我在理解代碼方面還是有困難。 因此,出於好奇,我試圖自己設計出邏輯,並提出了上面的代碼。
為什么這不起作用?
new[0::2]
返回一個沒有upper
方法的列表。 new[1::2]
及lower
。
您可以使用map
實現目標:
def myfunc2(string):
new = list(string)
new[0::2] = map(str.upper, new[0::2])
new[1::2] = map(str.lower, new[1::2])
return '' .join(new)
print(myfunc2('HelloWorld'))
# HeLlOwOrLd
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.