我有一个元组输入列表,其条目是:
input_1 = [('v1',['f1','f2','f3']),('v2',['f1','f2','f4']),('v3',['f1','f2','f4'])]
^^^^^^^^^ ^^^^^^^^^ ^^^^^^^^^
我想知道是否有办法获取包含“组”的元组列表,如下所示:
output_1 = [(['f1','f2'],['v1','v2','v3']) , (['f3'],['v1']), (['f4'],['v2','v3'])]
如果信息不够,其他输入/输出可能是:
input_2 = [('v1',['f1']),('v2',['f2','f3']),('v3',['f4'])]
output_2 = [(['f1'],['v1']) , (['f2','f3'],['v2']), (['f4'],['v3'])]
或
input_3 = [('v1',['f1','f2']),('v2',['f1','f2']),('v3',['f3']),('v4',['f1','f2'])]
^^^^^^^^^ ^^^^^^^^^ ^^^^^^^^^
output_3 = [(['f1','f2'],['v1','v2','v4']) , (['f3'],['v3'])]
我认为可能有一种方法可以通过实现字典来实现这一点,但我是 Python 新手,我无法从我见过的示例中弄清楚如何做到这一点:
Grouping integers by set membership in Python
Make sure all dicts in a list have the same keys
我认为我可以通过一堆 for 循环低效地做到这一点,但是有 pythonic 或干净的替代方案吗?抱歉,如果这个问题提出得不好,但感谢您的任何意见。
最佳答案
您可以遍历两个级别,然后重建输入以翻转级别;它可以帮助您大部分工作。主要问题是如何对共享 f
的 v
进行分组...有不同的排列可以给您提供与 Tim 建议的相同的结果。
无论如何:这是一个开始。
from collections import defaultdict
input_1 = [('v1',['f1','f2','f3']),
('v2',['f1','f2','f4']),
('v3',['f1','f2','f4'])]
input_2 = [('v1',['f1']),
('v2',['f2','f3']),
('v3',['f4'])]
input_3 = [('v1',['f1','f2']),
('v2',['f1','f2']),
('v3',['f3']),
('v4',['f1','f2'])]
def group(inp):
out = defaultdict(list)
for group in inp:
key = group[0]
for entry in group[1]:
out[entry].append(key)
return dict(out)
输出如下:
print group(input_1)
# {'f1': ['v1', 'v2', 'v3'],
# 'f2': ['v1', 'v2', 'v3'],
# 'f3': ['v1'],
# 'f4': ['v2', 'v3']}
print group(input_2)
# {'f1': ['v1'],
# 'f2': ['v2'],
# 'f3': ['v2'],
# 'f4': ['v3']}
print group(input_3)
# {'f1': ['v1', 'v2', 'v4'],
# 'f2': ['v1', 'v2', 'v4'],
# 'f3': ['v3']}
关于Python:按键集对列表进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18755734/