我正在制作一个简单的应用程序,它将根据类别从列表中随机弹出一个项目。我目前有两个类别(地点和姓名)。我试图创建两个函数。一个将随机返回其中一个类别(正常工作),另一个将获取随机类别,然后从该类别的列表中随机抽取
我的问题不是get_response
函数从列表中返回值,而是从列表名称中返回一个随机字符作为参数。有没有关于如何避开这个问题的想法。谢谢
这是我的密码:
from random import randrange
types = ["places", "names"]
places = ["The Upper Room", "Jerusalem", "Church", "Rome"]
names = ["Jesus", "Desciples", "Paul"]
def get_random_type():
return str(types[randrange(0, len(types))])
def get_response(chosentype):
return chosentype[randrange(0, len(chosentype))]
randtype = get_random_type()
print(randtype)
print(get_response(randtype))
编辑: 谢谢大家的帮助!多棒的社区啊
这是我最后的工作代码。这是多种答案的组合
import random
categories = ["places", "names"]
options = dict(places = ["The Upper Room", "Jerusalem", "Church", "Rome"],
names = ["Jesus", "Desciples", "Paul"])
def get_random_type():
return random.choice(categories)
def get_response(chosen_category):
category_items = options[chosen_category]
return random.choice(category_items)
print(get_response(get_random_type()))
问题在于,在第一个函数中,您传递一个迭代器(list),而在第二个函数中,您传递一个字符串作为迭代器,因此字符串“places”用于从中获取一个随机值,该值返回一个字符
我建议使用
random.choice
和eval
函数以更优雅的方式解决这个问题-因此,如果第一个函数选择“places”,那么
eval
函数将返回变量places
,即位置列表。使用另一个随机的。选择将给你一个随机的位置编辑:正如所指出的,
eval
函数可能是危险的,因为它可以允许某人编写一串代码作为输入,迫使你的应用程序运行代码。然而,只有不负责任地使用它才是危险的。在这种情况下,由于第一个函数被迫从预定义列表中返回一个选项,因此第二个函数的输入是安全的。如果您仍然想确保安全,可以执行以下操作如果您计划将此设置为Web应用程序的一部分,请阅读
eval
、它的滥用和优点使用词典。这是一个功能齐全的工作代码,它满足您的需求,只需对代码进行最少的更改
您可以使用dictionary和^{} 首先从
types
列表中选择一个随机项,使用该项输入字典,然后再次choice
从您选择的列表中选择一个随机项:在您的原始代码中,
chosentype[randrange(0, len(chosentype))]
不起作用,因为chosentype
是一个字符串,所以您实际上在做:这没什么意义。如果你想坚持这种设计,你必须坚持keying into globals as if it were a dictionary,或者写一个
if
-else
分支,这两个分支都不如上面的解决方案好相关问题 更多 >
编程相关推荐