Reputation: 59
I found this useful bit of code among the series of tubes that is the internet:
x=[1,2,3,4]
y=[1,2,3,4]
combos=[(`i`+`n`) for i in x for n in y]
combos
['11','12','13','14','21','22','23','24','31','32','33','34','41','42','43','44']
What I'm trying to do is something like the following:
combinations={(i: `n`+`d`) for i in range(16) for n in x for d in y}
combinations
{1: '11', 2: '12', 3: '13', 4: '14', 5: '21', 6: '22'...etc}
But obviously that's not working. Can this be done? If so, how?
Upvotes: 1
Views: 1205
Reputation: 13410
Also, there is a product
function in itertools
module that can be used here
from itertools import product
x=[1,2,3,4]
y=[1,2,3,4]
combs = {i+1: ''.join(map(str,p)) for i,p in enumerate(product(x,y))}
''.join(map(str,p))
is the code to convert all the items of p
(which is tuple
of int-s
) into str
and then join them using ''.join(...)
. If you don't need this, just leave p
instead of this code.
Also, note, that the syntax {j for j in js}
works only from Python 2.7
Upvotes: 1
Reputation: 287825
combos = [str(i) + str(n) for i in x for n in y] # or `i`+`n`, () for a generator
combinations = dict((i+1,c) for i,c in enumerate(combos))
# Only in Python 2.6 and newer:
combinations = dict(enumerate(combos, 1))
# Only in Python 2.7 and newer:
combinations = {i+1:c for i,c in enumerate(combos)}
Upvotes: 7
Reputation: 47988
You ... probably ... don't want that. At least, there's not a great reason to need it that I can see. if what you're after is being able to track their positions you want the result to be a list, which it already is. If you need to know the indexes you should do something like this:
for idx, combo in enumerate(combinations):
print idx+1, combo
If you actually need them accessible by position (and by list index + 1) you can do something like this:
lookup = dict((idx+1, combo) for idx, combo in enumerate(combinations))
Upvotes: 1
Reputation: 10820
Start with your first example:
x=[1,2,3,4]
y=[1,2,3,4]
combos=[(`i`+`n`) for i in x for n in y]
then just add:
combinations = {i: c for i, c in enumerate(combos)}
Upvotes: 1