python - 在函数中返回一个列表。另外,还有 while 循环的问题

标签 python list function while-loop

我在 Python 中创建函数时遇到问题。我希望我的功能允许用户在列表中输入单词,并询问用户是否愿意输入其他单词。如果用户输入“n”,我希望该函数返回列表中输入的单词。当我运行该函数时,它会询问用户是否愿意输入两次附加单词。此外,它不会返回列表。

def add_list(x):
    first_list = raw_input('Please input a word to add to a list ')
    x.append(first_list)
    response = None
    while response != 'n':
        response = raw_input('Would you like to enter another word? ')
        if response == 'n':
            print 'Here is the list of words'
            return x            
        else:
            add_list(x)


def main(): 
    add_list(x)


x = []
main()  

最佳答案

如上所述,您的代码不返回任何内容的原因是您实际上并未打印结果。此外,即使您已经说了“n”,它仍然继续询问您是否要输入另一个单词的原因是递归(即您以嵌套方式一遍又一遍地调用该函数(想想Excel 中的嵌套 IF,如果有帮助的话:))。一旦你掌握了基础知识,你就可以阅读更多内容,但现在我会避免它:)

这是一个基本版本的东西,可以做你想做的事情,其中​​的注释有望帮助你理解正在发生的事情:

def add_list():
    # Since you are starting with an empty list and immediately appending
    # the response, you can actually cut out the middle man and create
    # the list with the result of the response all at once (notice how
    # it is wrapped in brackets - this just says 'make a list from the
    # result of raw_input'
    x = [raw_input('Please input a word to add to a list: ')]

    # This is a slightly more idiomatic way of looping in this case. We
    # are basically saying 'Keep this going until we break out of it in
    # subsequent code (you can also say while 1 - same thing).
    while True:
        response = raw_input('Would you like to enter another word? ')

        # Here we lowercase the response and take the first letter - if
        # it is 'n', we return the value of our list; if not, we continue
        if response.lower()[0] == 'n':
            return x
        else:
            # This is the same concept as above - since we  know that we
            # want to continue, we append the result of raw_input to x.
            # This will then continue the while loop, and we will be asked
            # if we want to enter another word.
            x.append(raw_input('Please input a word to add to the list: '))

def main():
    # Here we return the result of the function and save it to my_list
    my_list = add_list()

    # Now you can do whatever you want with the list
    print 'Here is the list of words: ', my_list

main()

关于python - 在函数中返回一个列表。另外,还有 while 循环的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13435944/

相关文章:

python - 如何将列表的值与其索引的幂相加

python:从字符串创建列表

javascript - 如何让这个按钮只调用该函数一次?

python - 将数据从数据帧映射到另一个数据帧以提取信息用户

python - 二维核密度图的主要差异 : Seaborn and R

css - 当我的一些 li 有两行时,我怎么能在我的 ul li 上有破折号 (ipad)

java - 将字符串转换为日期的函数

java - java 函数 split() 的用法

python cherrypy - 如何添加标题

python - Spark 环境中的 pandas.read_csv (IBM Bluemix)