gpt4 book ai didi

python - 获取具有最大数字元素的元组,如果出现平局,则随机选择一个并列的元组

转载 作者:太空宇宙 更新时间:2023-11-04 00:12:30 25 4
gpt4 key购买 nike

我有一个元组列表:

a = [([4, 7, 9], [3], 5.5), ([2, 5, 8], [3], 5.5), ([2, 5, 8], [9], 4.5)]

我想获得具有最大数字元素的元组(非列表,例如 ([4, 7, 9], [3], 5.5) 中的 5.5 , 如果有平局,例如 ([4, 7, 9], [3], 5.5)([2, 5 , 8], [3], 5.5),将随机选择这些绑定(bind)元组之一作为输出。

到目前为止我的进步:

>>> import operator
>>> max(a, key = operator.itemgetter(1))
([3], [4, 7, 9], 5.5)

我不确定此时我如何随机选择一个绑定(bind)的元组。一些见解会很棒!

备注:要在每次运行 choice(.) 函数时都有不同的选择,请使用种子并执行:

r = random.Random(500) # seed number is arbitrary
r.choice(...)

最佳答案

解决方案:

m=max(a,key=lambda x: x[2])[2]
print(choice([i for i in a if i[2] == m]))

示例:

from random import choice
a = [([4, 7, 9], [3], 5.5), ([2, 5, 8], [3], 5.5), ([2, 5, 8], [9], 4.5)]
m=max(a,key=lambda x: x[2])[2]
print(choice([i for i in a if i[2] == m]))

解释:

  1. 遍历列表,然后取第三个(python 索引中为 2)的元素,然后根据第三个索引(python 索引中的第二个)的最大元素检查它,如果相同,则将其放入列出,否则,否

  2. 使用 random.choice(在我的例子中,因为我 from .. import .. 使用直接 choice,随机选择一个元素

关于python - 获取具有最大数字元素的元组,如果出现平局,则随机选择一个并列的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52023786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com