Skip to main content
 首页 » 编程设计

python之在 python 中用函数参数命名的列表

2025年05月04日11lhb25

我觉得这可能是我应该知道的,但我现在想不起来。我正在尝试获取一个函数来构建一个列表,其中列表的名称是函数中给出的参数;

例如

def make_hand(deck, handname): 
    handname = [] 
    for c in range(5): 
        handname.append(deck.pop()) 
    return handname 
 
    # deck being a list containing all the cards in a deck of cards earlier 

问题是这会创建一个名为 handname 的列表,当我希望它被称为用户在创建手时输入的 handname 时。

有人可以帮忙吗?谢谢

请您参考如下方法:

您可以保留一个字典,其中键是手的名称,值是列表。

然后您只需说字典[handname] 即可访问特定的手。沿着:

hands = {} # Create a new dictionary to hold the hands. 
hands["flush"] = make_hand(deck) # Generate some hands using your function. 
hands["straight"] = make_hand(deck) # Generate another hand with a different name. 
print hands["flush"] # Access the hand later.