python - 使用列表在python中调用函数内部的函数
问题描述
正在开始我的代码,我想做的是为我正在开发的一些彩票迷你游戏生成一个列表。它需要 10 个数字和 5 个字母,我运行一个函数来做到这一点,它工作得很好。然后我想设置获胜条件,所以我创建了另一个函数并使用该函数中的函数随机地用数字/字母填充列表。但是,当我尝试在获胜条件函数中填充列表时,它总是给我错误“无法从空序列中选择”。到目前为止,这是我的代码
import string
def fill_list(random_list):
random_list=[]
for i in range(0,10):
n=random.randint(1,10)
random_list.append(n)
for j in range(0,5):
n=random.choice(string.ascii_letters)
random_list.append(n)
return random_list
def win_condition(the_list):
the_list=[]
fill_list(the_list)
win_list=[]
for i in range(0,4):
n=random.choice(the_list)
win_list.append(n)
return win_list
#Error code
raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence
解决方案
这是您的代码中的问题(在行后的注释中):
def win_condition(the_list):
the_list=[] #the_list let an empty list
fill_list(the_list) #you invitate the fill_list() without data, and you get a list, that you dont use
win_list=[]
for i in range(0,4):
n=random.choice(the_list) #the_list is yet empty, the program can not do something with an empty list
win_list.append(n)
return win_list
试试看:
import string
def fill_list():
random_list=[]
for i in range(0,10):
n=random.randint(1,10)
random_list.append(n)
for j in range(0,5):
n=random.choice(string.ascii_letters)
random_list.append(n)
return random_list
def win_condition():
the_list=fill_list()
win_list=[]
for i in range(0,4):
n=random.choice(the_list)
win_list.append(n)
return win_list
我希望,这将是有用的 Nohab
推荐阅读
- c# - ML.Net 标签列第 7 行的错误值
- azure-active-directory - Azure AD 中的自定义错误消息或错误页面
- node.js - 在 MongoDB 中存储转换后的日期
- google-cloud-automl-nl - 一个自然语言模型可以应用多少个标签?
- c - 尽管我正在尝试更改数据类型,是否可以运行此代码?
- ace-editor - 王牌编辑器修改自动完成列表
- elasticsearch - 如何实现弹性搜索
- loops - 批处理嵌套循环在错误级别下无法正常工作
- angular - find() 不返回数据,只返回未定义
- python - Python pandas 仅在比较来自 csv 的日期时读取天数