简体   繁体   中英

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] . 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]] . 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.

Note: the numbers should be exact permutations, 112 and 121 count, but 112 and 122 don't.

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:

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)))) ; that is, map each number to a string made from a sorted list of the individual digits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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