繁体   English   中英

为什么我不能使用一个步骤来更改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.

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