python函数中的运行时错误(列表,实践中的字符串混淆问题)

python函数中的运行时错误(列表,实践中的字符串混淆问题),python,list,string-function,Python,List,String Function,我一直在尝试以我自己的业余方式从我的Python3训练营中解决一个特定的问题。到目前为止,我猜代码的append()行中有一个错误。在这里,我向您提供了预期的问题和答案。请帮我找出代码中的错误 尤达大师:给出一个句子,用单词返回一个句子 相反的尤达大师(“我在家”)-->“我在家”尤达大师(“我们在家”) 准备好了“)-->“我们准备好了” 您使用的索引错误。从-1开始,然后跳到0,因此将首先选择最后一个元素,然后选择第一个元素。相反,请使用以下代码: def master_yoda(text)

我一直在尝试以我自己的业余方式从我的Python3训练营中解决一个特定的问题。到目前为止,我猜代码的append()行中有一个错误。在这里,我向您提供了预期的问题和答案。请帮我找出代码中的错误

尤达大师:给出一个句子,用单词返回一个句子 相反的尤达大师(“我在家”)-->“我在家”尤达大师(“我们在家”) 准备好了“)-->“我们准备好了”


您使用的索引错误。从-1开始,然后跳到0,因此将首先选择最后一个元素,然后选择第一个元素。相反,请使用以下代码:

def master_yoda(text):
    mylist=text.split()
    newlist=[]
    index = -1
    for x in mylist:
        s = mylist[index]
        newlist.append(f"{s} ")  # to add a whitespace
        index = index - 1
    sentence = ""
    for y in newlist:
        sentence = sentence + y  # add the word
    return sentence
        
print(master_yoda("Here I am"))

您的
mylist
是一个列表列表,其中最外层的列表只有一个元素。例如,对于字符串“I am home”,
mylist
变为
[[“I”、“am”、“home”]]
。因此,对于mylist中的x,在循环
中它只迭代一次,
newlist
附加了
mylist[-1]
,即
[“我”、“我”、“家”]
。因此,当您加入它们时,输出结果与输入结果相同

现在,从您的问题描述可以清楚地看出,
我在家
变成了
我在家
。如果你仔细看,它只是颠倒了单词在句子中的位置(即第一个单词变为最后一个,第二个单词变为倒数第二个,依此类推)。所以你能做的就是把句子分成两部分,以列表的形式把单词排出来,然后把列表倒过来,把它连接起来

可以这样做-

def master_yoda(text):
    mylist = text.split() # notice that [] are omitted as text.split() itself returns a list
    return " ".join(mylist[::-1])
输入:

I am home
输出:

home am I

首先让我告诉您代码中的错误,以供您理解。然后我会给你不同的解决方案,你可以做你的代码。请在下面的代码中添加注释

def master_yoda(text):
        mylist=[text.split()] # The [] is not needed here, this is making list of list, ex. "We are ready" becomes [["We", "are", "ready"]]
        print(mylist)
        newlist=[]
        index=-1
        for x in mylist: # this is iterating each element of mylist (only one element is there, because above code created list of list, so outer list has only one element in it)
            newlist.append(mylist[index])
            index=index+1
        for y in newlist:
            print(" ".join(y))
# But anyway from the code you have written, I can see using similar things the requirment can be fulfilled without using any for loop.
忘掉所有这些,让我们按照你的方式去解决,我也会给你另一种方式

方式1:

def master_yoda(text):
        mylist=text.split()
        print(mylist)
        newlist=mylist[::-1]
        print(" ".join(newlist))
            
master_yoda("We are ready")
方式2: 下面的解决方案仅在一行中,没有使用循环和函数,我只是将上面代码中的所有行组合到一行中

print(" ".join("I am Your".split()[::-1]))
上述两个代码将给出以下输出

ready are we

如果您有任何疑问,请在评论中告诉我。

请不要尝试,它会按照通常的顺序打印句子(不会颠倒)。对。我的错。但是您可以在mylist[:-1]
ready are we