首页 > 解决方案 > 使用列表在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

标签: python

解决方案


这是您的代码中的问题(在行后的注释中):

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


推荐阅读