【发布时间】:2021-06-21 17:03:24
【问题描述】:
我有一个元组列表,用作函数的参数。我希望该函数随机选择列表中的一个元组(我使用的是 random.randint,但出于测试目的将其注释掉)并返回它。如果列表中的每个条目都是一个元组而不是一个条目,我该如何更改它?
announce_winner() 工作正常。我只是没有添加它。
def get_winner(*nominees):
# Should accept as nominees a list of items
winner = nominees[0]
#[random.randint(1, range(nominees))]
return winner
# Randomly pick one of the nominees (list items) as the winner
# Return the winner (list item) to the caller
def main():
best_original_score_list = [('Terence Blanchard','Da 5 Bloods'),
('Trent Reznor and Atticus Ross','Mank'),
('Emile Mosseri','Minari'),
('James Newton Howard','News of the World'),
('Trent Reznor, Atticus Ross, and Jon Batiste','Soul')]
announce_nominees('Best Original Score',best_original_score_list)
winner = get_winner(best_original_score_list)
main()
【问题讨论】:
-
不清楚你想要什么。您传入一个列表,然后在参数定义中解压缩该列表。
*有没有可能只是一个错字? -
“我怎样才能改变它,让列表中的每个条目都是一个元组而不是一个条目?”列表中的每个条目是一个元组。我不明白问题是什么。当您运行代码时,您期望发生什么?这与实际发生的情况有何不同?
-
您的代码中没有引用
announce_winner(),并且cmets 的位置非常混乱。请提供minimal reproducible example。 -
为了说明@MarcusMüller 的意思,请考虑一个最小的示例:尝试只使用
def test(*args): print(args),然后使用test([])。请注意它不打印[],而是打印([],)(即包含列表的元组)?这是因为参数列表中的*正在做什么,以便处理不同数量的参数。您在这里不想要或不需要它;拿出来。
标签: python function tuples arguments