gpt4 book ai didi

python - 处理一组独特的元组

转载 作者:太空宇宙 更新时间:2023-11-04 09:06:51 27 4
gpt4 key购买 nike

我有一组独特的元组,如下所示。第一个值是名称,第二个值是ID,第三个值是类型。

('9', '0000022', 'LRA')
('45', '0000016', 'PBM')
('16', '0000048', 'PBL')
('304', '0000042', 'PBL')
('7', '0000014', 'IBL')
('12', '0000051', 'LRA')
('7', '0000014', 'PBL')
('68', '0000002', 'PBM')
('356', '0000049', 'PBL')
('12', '0000051', 'PBL')
('15', '0000015', 'PBL')
('32', '0000046', 'PBL')
('9', '0000022', 'PBL')
('10', '0000007', 'PBM')
('7', '0000014', 'LRA')
('439', '0000005', 'PBL')
('4', '0000029', 'LRA')
('41', '0000064', 'PBL')
('10', '0000007', 'IBL')
('8', '0000006', 'PBL')
('331', '0000040', 'PBL')
('9', '0000022', 'IBL')

此集合包含重复的名称/ID 组合,但它们各自具有不同的类型。例如:

('9', '0000022', 'LRA')
('9', '0000022', 'PBL')
('9', '0000022', 'IBL')

我想做的是处理这组元组,以便我可以创建一个新列表,其中每个名称/ID 组合只出现一次,但包括所有类型。此列表应仅包含具有多种类型的名称/ID 组合。例如,我的输出看起来像这样:

('9', '0000022', 'LRA', 'PBL', 'IBL')
('7', '0000014', 'IBL', 'PBL', 'LRA')

但我的输出不应该包含只有一种类型的名称/ID 组合:

('45', '0000016', 'PBM')
('16', '0000048', 'PBL')

感谢任何帮助!

最佳答案

itertools.groupby对其输出的内容进行一些额外的处理就可以完成这项工作:

from itertools import groupby

data = {
('9', '0000022', 'LRA'),
('45', '0000016', 'PBM'),
('16', '0000048', 'PBL'),
...
}

def group_by_name_and_id(s):
grouped = groupby(sorted(s), key=lambda (name, id_, type_): (name_, id))
for (name, id_), items in grouped:
types = tuple(type_ for _, _, type_ in items)
if len(types) > 1:
yield (name, id_) + types

print '\n'.join(str(x) for x in group_by_name_and_id(data))

输出:

('10', '0000007', 'PBM', 'IBL')
('12', '0000051', 'LRA', 'PBL')
('7', '0000014', 'LRA', 'PBL', 'IBL')
('9', '0000022', 'LRA', 'PBL', 'IBL')

P.S. 但我不太喜欢这种设计:这些类型可能/应该是包含在元组的第 3 项中的列表,而不是元组本身的一部分...因为这元组的长度是动态的,这很丑陋......元组不应该那样使用。所以最好更换

        types = tuple(type_ for _, _, type_ in items)
yield (name, id_) + types

        types = [type_ for _, _, type_ in items]
yield (name, id_, types)

产生更干净的外观

('10', '0000007', ['IBL', 'PBM'])
('12', '0000051', ['LRA', 'PBL'])
('7', '0000014', ['IBL', 'LRA', 'PBL'])
('9', '0000022', ['IBL', 'LRA', 'PBL'])

例如,您可以使用 for name, id, types in transformed_data: 迭代结果数据。

关于python - 处理一组独特的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19800454/

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