Python从列表名而不是列表项返回字符

2024-09-30 02:36:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个简单的应用程序,它将根据类别从列表中随机弹出一个项目。我目前有两个类别(地点和姓名)。我试图创建两个函数。一个将随机返回其中一个类别(正常工作),另一个将获取随机类别,然后从该类别的列表中随机抽取

我的问题不是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()))

Tags: 列表getreturnnamesresponsedeftyperandom
3条回答

问题在于,在第一个函数中,您传递一个迭代器(list),而在第二个函数中,您传递一个字符串作为迭代器,因此字符串“places”用于从中获取一个随机值,该值返回一个字符

我建议使用random.choiceeval函数以更优雅的方式解决这个问题-

import random

def get_random_type():
    return random.choice(types)

def get_response(chosentype):
    return random.choice(eval(chosentype))

randtype = get_random_type()
print(randtype)
print(get_response(randtype))
places
The Upper Room

因此,如果第一个函数选择“places”,那么eval函数将返回变量places,即位置列表。使用另一个随机的。选择将给你一个随机的位置

编辑:正如所指出的,eval函数可能是危险的,因为它可以允许某人编写一串代码作为输入,迫使你的应用程序运行代码。然而,只有不负责任地使用它才是危险的。在这种情况下,由于第一个函数被迫从预定义列表中返回一个选项,因此第二个函数的输入是安全的。如果您仍然想确保安全,可以执行以下操作

def get_response(chosentype):
    if chosentype in types:
        return random.choice(eval(chosentype))

如果您计划将此设置为Web应用程序的一部分,请阅读eval、它的滥用和优点

使用词典。这是一个功能齐全的工作代码,它满足您的需求,只需对代码进行最少的更改

from random import randrange

config = {
   "places": ["The Upper Room", "Jerusalem", "Church", "Rome"],
   "names": ["Jesus", "Desciples", "Paul"]
}

def get_random_type():
    types = list(config.keys())
    return str(types[randrange(0, len(types))])

def get_response(chosentype):
    return config[chosentype]

randtype = get_random_type()
print(randtype)
print(get_response(randtype))

您可以使用dictionary^{}首先从types列表中选择一个随机项,使用该项输入字典,然后再次choice从您选择的列表中选择一个随机项:

>>> from random import choice
>>> types = ["places", "names"]
>>> options = dict(
...     places=["The Upper Room", "Jerusalem", "Church", "Rome"],
...     names=["Jesus", "Desciples", "Paul"]
... )
>>> choice(options[choice(types)])
Desciples

在您的原始代码中,chosentype[randrange(0, len(chosentype))]不起作用,因为chosentype是一个字符串,所以您实际上在做:

>>> "foobar"[randrange(0, len("foobar"))]
'o'

这没什么意义。如果你想坚持这种设计,你必须坚持keying into globals as if it were a dictionary,或者写一个if-else分支,这两个分支都不如上面的解决方案好

相关问题 更多 >

    热门问题