Linell
Linell

Reputation: 749

Permutations of Digits in Python

I have the four digit permutations of digits 0-9, and all of these are stored in a big list. (0, 1, 2, 3)(0, 1, 2, 4)(0, 1, 2, 5)(0, 1, 2, 6), etc.

But! I want these to be stored differently. I want 0123, 0124, 0125, 1026, etc. How can I change make each item in the list join into a single item?

Upvotes: 0

Views: 1398

Answers (5)

rav
rav

Reputation: 3688

Try this one:

[ reduce(lambda x,y: str(x) + str(y), list) for list in lists]

Join version:

[ reduce(lambda x,y: ''.join((x,y)), map(str,list)) for list in lists]

Both versions for integers, if elements are string skip mapping to string :)

Upvotes: 3

the wolf
the wolf

Reputation: 35552

Use a list comprehension with format:

>>> l=[(0, 1, 2, 3), (0, 1, 2, 4), (0, 1, 2, 5), (0, 1, 2, 6)]
>>> ['{}{}{}{}'.format(*t) for t in l]
['0123', '0124', '0125', '0126']

Works for ints or strings in the tuples:

>>> l=[(0, 1, 2, 3), (0, 1, 2, 4), (0, 1, 2, 5), (0, 1, '2', 6)]
>>> ['{}{}{}{}'.format(*t) for t in l]
['0123', '0124', '0125', '0126'] 

If you want ints, you can use map on the output of the LC:

>>> map(int,['{}{}{}{}'.format(*t) for t in l])
[123, 124, 125, 126]

Use join if tuples might be variable length:

>>> l=[(0, 1, 2, 3), (0, 1, 2, 4), (0, 1, 2, 5), (0, 1, '2')]
>>> [''.join(map(str,t)) for t in l]
['0123', '0124', '0125', '012']

Upvotes: 2

unutbu
unutbu

Reputation: 880419

In [11]: seq = [(0, 1, 2, 3), (0, 1, 2, 4), (0, 1, 2, 5), (0, 1, 2, 6)]

In [12]: [''.join(map(str, item)) for item in seq]
Out[12]: ['0123', '0124', '0125', '0126']

Upvotes: 1

Tadeck
Tadeck

Reputation: 137420

Assuming the "digits" are strings (and not integers), do it like this:

result = map(''.join, long_list)

Alternatively this will work for strings and integers:

result = map('{[0]}{[1]}{[2]}{[3]}'.format, longlist)

Or use itertools.imap() for performance.

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799150

>>> reduce(lambda x, y: x * 10 + y, (0, 1, 2, 3))
123

>>> '%04d' % (reduce(lambda x, y: x * 10 + y, (0, 1, 2, 3)),)
'0123'

Upvotes: 8

Related Questions