gpt4 book ai didi

python - 嵌套列表 : Count, 最大值和最小值

转载 作者:太空宇宙 更新时间:2023-11-04 04:42:22 24 4
gpt4 key购买 nike

我有一个嵌套列表:

data = [[12345678, 14, 1],[135763365, 14, 0],[135763365, 12, 0],[1234, 9, 0]]

我想在其中找到所有子列表的最大索引 1。

为此我创建了这个函数:

def findBusiestPeriod ():
result = max([item[1] for item in data])
counter = collections.Counter(itertools.chain(*data))
if counter[result] > 2:
# Here's where I want to find the smallest index[0] based on
# the max index[1]

return result

一旦我有了列表的最大索引 1,我想检查是否有重复项(示例中有。)如果有重复项,我只想返回子列表具有最小索引 0

我该怎么做?

最佳答案

sorted() 可以用这样的键来做到这一点:

代码:

sorted(data, key=lambda x: (-x[1], x[0]))[0]

测试代码:

data = [[12345678, 14, 1], [135763365, 14, 0],
[135763365, 12, 0], [1234, 9, 0]]

print(sorted(data, key=lambda x: (-x[1], x[0]))[0])

结果:

[12345678, 14, 1]

关于python - 嵌套列表 : Count, 最大值和最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50363050/

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