Question

Say I have a method:

def add_force_coupling(g1, g2, name):
    print {(g1,g2): name}

then the code:

l = 3
for g1 in range(l):
    for g2 in range(l):
      name = 'G' + str(g1) + str(g2)
      add_force_coupling(g1, g2, name)

produces the result:

{(0, 0): 'G00'}, {(0, 1): 'G01'}, {(0, 2): 'G02'}, {(1, 0): 'G10'}, ..., {(2, 2): 'G22'}

Now I want to make this more pythonic by using the map() function. So far I have got:

list1 = sorted(l*range(l))
list2 = l*range(l)
list3 = ["".join(values) for values in zip(l*l*'G',list(map(str,l1)),list(map(str,l2)))]
map( add_force_coupling, list1, list2, list3 )

which does exactly what I want but is uglier than the standard double loop since the int list need to be converted to str in list3. Also it is quite difficult to understand what is going on. Is there any better pythonic way of rewriting the double loop with a map(), zip() or otherwise?

Note: changing the method is not an option

Was it helpful?

Solution

Don't use map(). Use a list comprehension and itertools.product():

from itertools import product

[{(i, j): 'G{}{}'.format(i, j)} for i, j in product(range(l), repeat=2)]

or using your function for the left-hand expression:

[add_force_coupling(i, j, 'G{}{}'.format(i, j))
 for i, j in product(range(l), repeat=2)]

It does strike me that you are looking to build one dictionary here; a dict comprehension could do that:

{(i, j): 'G{}{}'.format(i, j) for i, j in product(range(l), repeat=2)}

Here you can address each item with result[i, j].

but given the indices, a nested list would be a more efficient storage mechanism for the data:

[['G{}{}'.format(i, j) for j in range(l)] for i in range(l)]

and address results with

result[i][j]

OTHER TIPS

dont use a map or a dictionary this is naturally represented as a 2d list

data = [['G{0}{1}'.format(j,i) for i in range(l)] for j in range(l)]

data[0][0]
print data[0][1] 
...

hmm the note at the end makes me thing that this is perhaps not what OP needs ... but it is still a more appropriate solution to the general problem here (at least imho)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top