简体   繁体   English

组号(如果它们在Python中彼此置换)

[英]Group numbers if they are permutations of each other in Python

I have a list of numbers, let's say [1091, 2053, 4099, 4909, 5023, 9011] . 我有一个数字列表,比如[1091, 2053, 4099, 4909, 5023, 9011] Here every number has it's permutation in a list too. 在这里,每个数字也在列表中进行排列。 Now i want to group these permutations of each other, so the list becomes [[1091, 9011], [2053, 5023], [4099, 4909]] . 现在,我想将这些排列彼此分组,因此列表变为[[1091, 9011], [2053, 5023], [4099, 4909]] I know how to use groupby and permutations , but have no idea, what should be they key for groupby or how should i solve the problem some other way. 我知道如何使用groupbypermutations ,但不知道,它们对于groupby应该是什么关键,或者我应该如何以其他方式解决问题。

Note: the numbers should be exact permutations, 112 and 121 count, but 112 and 122 don't. 注意:数字应为精确排列,112和121计数,但112和122则不然。

How to group permutations of a number in a list? 如何对列表中的数字排列进行分组?

import itertools as it
a = [1091, 2053, 4099, 4909, 5023, 9011]
sort_string = lambda x: sorted(str(x))
[[int(x) for x in v] for k,v in it.groupby(sorted(a, key=sort_string), key=sort_string)]
# [[1091, 9011], [2053, 5023], [4099, 4909]]

You can use collections.Counter to represent each number as a tuple of integer, total_occurrences and then store all the data in instances in a dictionary: 您可以使用collections.Counter将每个数字表示为integer, total_occurrences的元组,然后将所有数据存储在字典的实例中:

from collections import Counter, defaultdict

dest = defaultdict(list)
data = [1091, 2053, 4099, 4909, 5023, 9011]

data = ((Counter([int(x) for x in str(datum)]), datum) for datum in data)
for numbers, value in data:
    numbers = tuple(sorted(numbers.items()))
    dest[numbers].append(value)

print dest.values()
# [[1091, 9011], [2053, 5023], [4099, 4909]]

Represent each number with a normalization which fits your purpose. 用适合您目的的归一化表示每个数字。 For your example, a suitable canonical form could be "".join(sort("".split(str(n)))) ; 在您的示例中,合适的规范形式可以是"".join(sort("".split(str(n)))) that is, map each number to a string made from a sorted list of the individual digits. 也就是说,将每个数字映射到由各个数字的排序列表组成的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM