gpt4 book ai didi

python - 根据列表中的以下元素获取第一个元素的范围

转载 作者:太空宇宙 更新时间:2023-11-03 14:29:43 24 4
gpt4 key购买 nike

我正在努力解决以下问题。基本上我有一个列表:

dolist = [(1280, ['A1'], ['A2']), (1278, ['A1'], ['A2']), (1276, ['A1'], ['A2']), (1274, ['B1'], ['B2']), (1272, ['A1'], ['A2']), (1270, [], ['A2'])]

现在我想让列表按元素 2 和 3 排序。

uniqdo = [ (['A1'],['A2']), (['B1'],['B2']),([],['A2']) ]
dorange = [ "1280-1276,1272","1274","1270" ]

我尝试进行直接比较,但是经过多次测试代码变得很长并且看起来有点困惑。必须有库函数可以合理快速地完成此操作。

最佳答案

看起来像itertools.groupby可以帮助你:

>>> dolist = [ (1280,['A1'],['A2']),(1278,['A1'],['A2']),(1276,['A1'],['A2']),(1274,['B1'],['B2']),(1272,['A1'],['A2']) ]
>>> from itertools import groupby
>>> [[v, [i for i,*_ in g]] for v, g in groupby(dolist, key= lambda l: (l[1][0], l[2][0]))]
[[('A1', 'A2'), [1280, 1278, 1276]], [('B1', 'B2'), [1274]], [('A1', 'A2'), [1272]]]

将上述数据结构转换为您想要的数据结构应该不难。

这是一个开始。您不能将任何列表保留为输入,因为 Python 列表不能用作字典键。因此 get_value 返回 None 而不是空列表:

from itertools import groupby

dolist = [(1280, ['A1'], ['A2']), (1278, ['A1'], ['A2']), (1276, ['A1'], ['A2']), (1274, ['B1'], ['B2']), (1272, ['A1'], ['A2']), (1270, [], ['A2'])]
ranges = {}


def get_value(l):
if l:
return l[0]
else:
return None


def get_values(t):
return (get_value(t[1]), get_value(t[2]))

for v, g in groupby(dolist, get_values):
ids = [str(t[0]) for t in g]
if len(ids) > 1:
range_str = ids[0] + '-' + ids[-1]
else:
range_str = ids[0]
ranges.setdefault(v, []).append(range_str)

print(ranges)
# {('A1', 'A2'): ['1280-1276', '1272'], ('B1', 'B2'): ['1274'], (None, 'A2'): ['1270']}

关于python - 根据列表中的以下元素获取第一个元素的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47388736/

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