尝试学习循环和/或如果政治家

2024-09-30 08:15:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚开始学习python,我想知道它怎么了 这是for循环和/或if语句。你知道吗

我试着循环一系列单词,如果我发现 一个词“right”我想用“left”来代替它。你知道吗

def left_join(phrases):                
"""                 
    Join strings and replace "right" to "left"            
"""               

    mlist = list(phrases) 

    for word in mlist:

        if word == "right":
             word = "left"

    output = ','.join(mlist)
    return output    

phrases = ("left", "right", "left", "stop")
left_join(phrases)  

我应该得到这个

"left,left,left,stop"

但我明白了

"left,right,left,stop"

所以“右”不能用“左”代替。为什么?你知道吗


Tags: rightforoutputifdef语句单词left
2条回答

请尝试以下代码:

def left_join(phrases):                
    """                 
         Join strings and replace "right" to "left"            
    """               

    mlist = list(phrases) 

    for i  in range(len(mlist)):

        if mlist[i] == "right":
            mlist[i] = "left"

    output = ','.join(mlist)
    return output    

phrases = ("left", "right", "left", "stop")
output = left_join(phrases)
print(output)

引用official documentation on for loop

An iterator is created for the result of the expression_list. The suite is then executed once for each item provided by the iterator, in the order of ascending indices.

所以mlist没有改变,这里只改变了word

相关问题 更多 >

    热门问题