将用户输入添加到列表的功能 [英] Function to add user inputs to a list

查看:142
本文介绍了将用户输入添加到列表的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  def answers_body():


user_preference = []
user_preference.extend(input(Please enter your answer:))

我的问题真的归结为;我怎么能重新写这个,这样列表不会在每次被调用时被清除?我避免使用这个程序的全局变量;由于这个原因,我非常感谢更多有经验的程序员提供一些关于如何纠正这个问题的建议,而不需要使用全局变量/列表。

谢谢。

一种方法是在你的函数调用之外放置 preference_list

解决方案我建议您使用 list.append ,而不是因为 list.extend 主要用于将多个值添加到列表中。

  preference_list = [] 
def answers_body(body):
body.append(input(请输入您的答案:))
为范围内的我(10):
answers_body(首选项)
print(preference_list)

您还可以将 preference_list 保存到 answers_body 的namescope,如果你没有它作为全局变量。

  def answers_body():
answers_body.preference_list。附加(输入(请输入您的答案:))

answers_body.preference_list = []
在范围内(10):
answers_body()
print(answers_body.preference_list)


I've been having some trouble getting the logic to work properly for the below function:

def answers_body():
   user_preference = []
   user_preference.extend(input("Please enter your answer: "))

My question really comes down to; how can I re-write this so the list doesn't get cleared each time it's called? I'm avoiding using Global Variables for this program; due to this, I'd really appreciate any more experienced programmers giving some advice on how to rectify this without resorting to a global variable/list.

Thank you.

解决方案

One way is to place preference_list outside of your function call. And I would recommend you to use list.append instead because list.extend is mainly used to add multiple values to list.

preference_list = []
def answers_body(body):
    body.append(input("Please enter your answer: "))
for i in range(10):
    answers_body(preference)
print(preference_list)

You can also save preference_list into answers_body's namescope if you don't what it as a global variable.

def answers_body():
    answers_body.preference_list.append(input("Please enter your answer: "))

answers_body.preference_list = []
for i in range(10):
    answers_body()
print(answers_body.preference_list)

这篇关于将用户输入添加到列表的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆