我有一个嵌套列表:
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]
