Python:按键集对列表进行分组

标签 python list key set tuples

我有一个元组输入列表,其条目是:

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 或干净的替代方案吗?抱歉,如果这个问题提出得不好,但感谢您的任何意见。

最佳答案

您可以遍历两个级别,然后重建输入以翻转级别;它可以帮助您大部分工作。主要问题是如何对共享 fv 进行分组...有不同的排列可以给您提供与 Tim 建议的相同的结果。

Different output grouping permutations...which is more valid?

无论如何:这是一个开始。

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/

相关文章:

html - 在 Bootstrap 3 响应式设计中将水平列表居中

java - 删除彼此相邻的重复项

java - 使用哈希表比较值

ios - 在 AnimationDidStop 中检索 CAKeyframeAnimationKey 的键

python - 使用 Flask 和 Flask-MongoAlchemy 时的 WTForms 语法

python - 在 tkinter Canvas 上跟踪自己的对象

python - 在行和列中拆分数组

python - 使用嵌套 for 循环、条件和累加器的列表理解

python - 获取对象列表中属性值最大的对象列表

JSON 字段具有相同的名称