Home > front end >  Difficulty in list comprehension while a nested for loop could be nasty
Difficulty in list comprehension while a nested for loop could be nasty

Time:01-24

I need to get (-2.0EMEXW_1_M_Xx1/F - 2.0ENEXW_1_N_Xx1/F) in my code. Everything is working well using the nested for loop while if I want to get result using the list comprehension then it(aasum) gives duplicate elements.

import sympy as sp
anions = {'X': 1 }
cations = {'M': 1, 'N': 1}
neutrals = {'1' : 0}
aa = list(-(1 / sp.symbols(f'F')) * sp.symbols(f'E{m}') * sp.symbols(f'E{n}') * \
                            ((x   y) / (x * y)) * sp.symbols(f'x{str(list(neutrals.keys())[0])}') *       sp.symbols(f'W_{str(list(neutrals.keys())[0])}_{str(m)}_{str(n)}') \
                            for m in cations.keys() \
                            for x in cations.values() \
                            for n in anions.keys() \
                            for y in anions.values())

aasum = sum(aa)
asum = 0.0
for k in anions:
    for j in cations:
        for n in neutrals:
            asum  = -(1 / sp.symbols(f'F')) * sp.symbols(f'E{str(j)}') * sp.symbols(f'E{str(k)}') * \
            ((cations[j]   anions[k]) / (cations[j] * anions[k])) * sp.symbols(f'x{str(list(neutrals.keys())[0])}') *\
                 sp.symbols(f'W_{str(list(neutrals.keys())[0])}_{str(j)}_{str(k)}')

print(asum,'...', aasum) 

result is: asum:-2.0EMEXW_1_M_Xx1/F - 2.0ENEXW_1_N_Xx1/F ... aasum:-4.0EMEXW_1_M_Xx1/F - 4.0ENEXW_1_N_Xx1/F I checked: [https://stackoverflow.com/questions/64091392/nested-list-in-list-comprehension-to-for-loop] But it has nothing to do answering my question. Any suggestion to get correct result using list comprehension would be welcomed.

CodePudding user response:

Use items instead of keys and values:

import sympy as sp
anions = {'X': 1 }
cations = {'M': 1, 'N': 1}
neutrals = {'1' : 0}
aa = [-(1 / sp.symbols(f'F')) * sp.symbols(f'E{m}') * sp.symbols(f'E{n}') *
      ((x   y) / (x * y)) * sp.symbols(f'x{str(list(neutrals.keys())[0])}') * sp.symbols(f'W_{str(list(neutrals.keys())[0])}_{str(m)}_{str(n)}')
          for (m, x) in cations.items()
          for (n, y) in anions.items()]

Output:

>>> aa
[-2.0*EM*EX*W_1_M_X*x1/F, -2.0*EN*EX*W_1_N_X*x1/F]

>>> sum(aa)
-2.0*EM*EX*W_1_M_X*x1/F - 2.0*EN*EX*W_1_N_X*x1/F

Explanation:

In your loop, you iterate over keys only so you get the cartesian product of anions x cations. In your comprehension, you iterate both on keys ans values so you have the product of cations.values x cations.keys, x anions.values x anions.keys. What I did was replicate what you did in your loop except I get the keys and values at the same time. I have the product of (anions.keys, anion.values) x (cations.keys, cations.values). It avoid j and k indexes.

  • Related