如何查找和分组 4 位数字的相似排列

How to find and group similar permutations of 4 digits

我不擅长这些,但请多多包涵。我的数据库/列表中有一组数字,都是 4 位数字,数字介于 0000 到 9999 之间。

假设列表是:

[1234, 4354, 6554, 2134, 3214, 5456, 9911, 1199]

基本上我想这样分组

1234, 2134, 3214 is group A
6554, 5456 is group B
9911, 1199 is group C
4354 is group D

每个组中的列表项都包含相同的数字 - 即组 A 全部由数字 1、2、3 和 4 组成。然后我会找到 len(group A),len (B组), len(C组), len(D组)... 然后按降序排列。

怎么做? 如果列表很大,该方法是否仍然有效?

这是一个(在 Python 2.7.10 中测试过)的解决方案:

def index(number):
    digits = list(str(number))
    return ''.join(sorted(digits))

groups = {}
numbers = [1234, 4354, 6554, 2134, 3214, 5456, 9911, 1199]

for number in numbers:
    key = index(number)

    if key not in groups:
        groups[key] = []

    groups[key].append(number)

print groups.values() # [[1234, 2134, 3214], [4354], [6554, 5456], [9911, 1199]]

这个解决方案的关键是取每个数字的数字并对它们进行排序,然后使用该结果作为字典键。 index() 只是生成每个数字的数字排序形式的简洁方法。

不确定要如何命名组,但可以在将整数转换为字符串并对这些字符进行排序后使用itertools.groupby

from itertools import groupby

l = [1234, 4354, 6554, 2134, 3214, 5456, 9911, 1199]

# ints to (int, sorted str)
s = map(lambda x: (x, ''.join(sorted(str(x)))), l)

# sort the list for groupby
s.sort(key=lambda kv: kv[1])

# print out just the ints of the groups
for _, g in groupby(s, lambda kv: kv[1]):
    print map(lambda kv: kv[0], g)

输出

[9911, 1199]
[1234, 2134, 3214]
[4354]
[6554, 5456]