简体   繁体   English

为什么我不能使用一个步骤来更改Python列表中的项目?

[英]Why can't I change items in a Python list using a step?

So I am still in the beginning stages of learning Python--and coding as a whole for that matter. 因此,我仍处于学习Python的初期阶段,并为此进行整体编码。

My question is why can I not change items in a Python list using a step, like this: 我的问题是为什么我不能使用以下步骤更改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')

I want to make every other letter upper and lower case, starting at index 0. 我想使其他所有字母都大写和小写,从索引0开始。

I had already seen a solution posted by another user, and although this other solution worked I had trouble understanding the code. 我已经看到了另一个用户发布的解决方案,尽管这个其他解决方案有效,但是我在理解代码方面还是有困难。 So, in my curiosity I tried to work out the logic myself and came up with the above code. 因此,出于好奇,我试图自己设计出逻辑,并提出了上面的代码。

Why is this not working? 为什么这不起作用?

new[0::2] returns a list, which does not have an upper method . new[0::2]返回一个没有upper方法的列表。 Same goes for new[1::2] and lower . new[1::2]lower

You can achieve your goal with map : 您可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM