-1

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

MASTER YODA:给定一个句子,返回一个单词颠倒的句子 master_yoda('I am home') --> 'home am I' master_yoda('We are ready') --> 'ready are We'

def master_yoda(text):
        mylist=[text.split()]
        print(mylist)
        newlist=[]
        index=-1
        for x in mylist:
            newlist.append(mylist[index])
            index=index+1
        for y in newlist:
            print(" ".join(y))
4

3 回答 3

0

mylist是一个列表列表,其中最外面的列表只有一个元素。Fox 示例,对于字符串“I am home”,mylist变为[["I", "am", "home"]]. 因此,在循环中for x in mylist它只迭代一次并newlist附加了mylist[-1]which is ["I", "am", "home"]。因此,当您加入它们时,输出与输入相同。

现在从您的问题描述中,很明显I am home变成home am I. 如果仔细观察,它只是颠倒了句子中单词的位置(即第一个单词变成最后一个单词,第二个变成倒数第二个单词,依此类推)。所以你可以做的是拆分句子以获取列表格式的单词并将列表反转并加入它。

这可以这样做 -

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
于 2021-05-24T07:32:01.143 回答
0

您使用的索引错误。您从 -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"))
于 2021-05-24T07:30:40.207 回答
0

让我先告诉你你的代码有什么问题,以便你理解。然后我会给你不同的解决方案,你可以对你的代码做。请在下面的代码中发表评论。

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

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

于 2021-05-24T08:11:07.900 回答