python 查询-函数参数类型不正确?

标签 python

我是 python 的新手,我在将参数传递给 random.choice 函数时遇到了问题。

基本上我正在尝试编写一个循环,该循环将从“a”列表中选择一个随机字母(其他列表的所有名称)开始,然后再次将所选字母输入 random.choice 以生成一个随机字母序列。

不幸的是,对 random.choice 的第二次调用不起作用,它只是不断重复输入的字母,而不是指向新列表。任何想法如何解决这一问题?我一直在网上寻找几个小时,但找不到任何类似的问题/解决方案。任何帮助将不胜感激!

import random

a = ['b','c','d']
b = ['a','e']
c = ['a','d','f']
d = ['a','c','e','f','g','h']
e = ['b','d','h']
f = ['c','d','g','i']
g = ['d','f','i']
h = ['d','e','g','i']
i = ['f','h']

x = 0
answer = random.choice(f)
print "answer is %s " % answer

while x < 5:
    answer2 = random.choice(answer) 
    print "answer2 is now %s " % answer2
    x = x + 1

最佳答案

您已陷入混淆变量和数据并试图将您的代码视为数据的常见初学者陷阱。您通常不应该尝试这样做 - 不要将一个变量的名称放入另一个变量中并尝试以这种方式访问​​它。

相反,将所有数据保存在一个数据结构中,只使用您的变量来访问该结构,如下所示:

import random

DATA = {
    'a': ['b','c','d'],
    'b': ['a','e'],
    'c': ['a','d','f'],
    'd': ['a','c','e','f','g','h'],
    'e': ['b','d','h'],
    'f': ['c','d','g','i'],
    'g': ['d','f','i'],
    'h': ['d','e','g','i'],
    'i': ['f','h'],
}

x = 0
answer = random.choice(DATA['f'])
print "answer is %s " % answer

while x < 5:
    answer2 = random.choice(DATA[answer]) 
    print "answer2 is now %s " % answer2
    x = x + 1

关于python 查询-函数参数类型不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7055667/

相关文章:

python - 什么时候可以在 Google App Engine 中抛出 DeadlineExceededError 异常

python - 在 Python 中使用 CV2 和 Pyglet 捕获网络摄像头图像

python - Django:如何构建一个endswith模板过滤器

python - 检测异常类型

python - URI 正则表达式模式匹配

python - QPushButton 内的 PyQt QHBoxLayout 文本被截断

python - 如何使用 python 通过 beautifulsoup 检索文本

意外标记附近的 Python 语法错误

Python:使用 wmi 远程启动可执行文件

python - Flask-sqlalchemy - 用户查询 'BaseQuery' 对象没有属性 'password'