带有map和lambda函数的Python字符串问题

带有map和lambda函数的Python字符串问题,python,string,dictionary,lambda,Python,String,Dictionary,Lambda,我编写了一个python函数,该函数应该接受一个字符串,并返回相同的字符串,每个单词的大小写都是偶数索引字符,每个单词的大小写都是奇数索引字符 例如:to_-weird_-case('weird-string-case')#=>返回'weird-string-case' def to_weird_case(string): s = list(string.split(" ")) words = [] for word in s: w = map(lambd

我编写了一个python函数,该函数应该接受一个字符串,并返回相同的字符串,每个单词的大小写都是偶数索引字符,每个单词的大小写都是奇数索引字符
例如:to_-weird_-case('weird-string-case')#=>返回'weird-string-case'

def to_weird_case(string):
    s = list(string.split(" "))
    words = []
    for word in s:
        w = map(lambda x: x.upper() if word.index(x)%2 == 0 else x.lower(), word)
        w = "".join(list(w))
        words.append(w)

    #print(words)
    return " ".join(words)
现在我的问题是:一旦超过一个单词被传递,最后一个单词的最后几个字母都被转换成大写,我不明白为什么
例如:to_wird_case(“这是一个测试”)返回这是一个测试


感谢您的帮助

这是因为
index()
函数以字符串形式返回该字符的第一个实例的索引。您需要的是使用enumerate编写循环:

对于索引,枚举中的单词:


使用此函数,而不是使用index函数,您可以基于从
enumerate()

传递的
index
变量编写逻辑,这是因为
index()
函数返回字符串中该字符第一个实例的索引。您需要的是使用enumerate编写循环:

对于索引,枚举中的单词:


使用此函数,而不是使用index函数,您可以基于从
enumerate()

word传递的
index
变量编写逻辑。index
找不到您当前查看的字母的索引,它查找字符串中第一次出现的字符的索引…
word.index
找不到您当前正在查看的字母的索引,它查找字符串中第一次出现的字符的索引…