Ponx
Ponx

Reputation: 97

How to turn nested loops into list comprehension that keep track of inner loop?

Is there a way to make this list comprehension to produce the wanted output like I written down ?

year_diff = [(1-(np.absolute(x-y)/2005)) for x in excluded_books_over10['yearOfPublication'] for y in years]

Output:

[0.999002493765586, 0.9980049875311721, 0.9940149625935162, 0.9980049875311721, 0.9955112219451372, 0.9980049875311721, 0.999002493765586, 0.9995012468827931, 0.9985037406483791, 0.9965087281795512, 1.0, 0.9985037406483791, 0.9925187032418953, 0.9995012468827931, 0.9950124688279302, 0.9960099750623441, 0.9985037406483791, 0.9955112219451372, 0.999002493765586, 0.9995012468827931, 0.9995012468827931, 0.9970074812967581, 0.9985037406483791, 0.9980049875311721, 0.9925187032418953, 0.9945137157107232, 0.9915211970074813, 0.9940149625935162, 0.9875311720698254, 0.9955112219451372, 0.9955112219451372, 0.9975062344139651, 0.9970074812967581, 1.0, 0.9900249376558603,....

This code produce the result that I want.

new_list = []
for x in excluded_books_over10['yearOfPublication']:
    temp_list = []
    for y in years:
        temp_list.append(1-(np.absolute(x-y)/2005))
    new_list.append(temp_list)
print(new_list)

Output :

[[0.999002493765586, 0.999002493765586], [0.9980049875311721, 1.0], [0.9940149625935162, 0.9960099750623441], [0.9980049875311721, 1.0], [0.9955112219451372, 0.9975062344139651], [0.9980049875311721, 1.0], [0.999002493765586, 0.999002493765586], [0.9995012468827931, 0.9975062344139651], [0.9970074812967581, 0.999002493765586], [0.9985037406483791, 0.9995012468827931], [0.9965087281795512, 0.9985037406483791], [1.0, 0.9980049875311721], [0.9985037406483791, 0.9995012468827931], [0.9925187032418953, 0.9945137157107232], [0.9995012468827931, 0.9985037406483791], [0.9950124688279302, 0.9970074812967581], [0.9960099750623441, 0.9980049875311721], [0.9985037406483791, 0.9995012468827931], [0.9955112219451372, 0.9975062344139651], [0.999002493765586, 0.999002493765586], [0.9995012468827931, 0.9985037406483791], [0.9995012468827931, 0.9985037406483791], [0.9970074812967581, 0.999002493765586], [0.9985037406483791, 0.9995012468827931], ...

Thanks everyone in advance and feel free to edit if I have done something wrong.

Solution by Swazy :

year_diff = [[(1-(np.absolute(x-y)/2005)) for y in years] for x in excluded_books_over10['yearOfPublication']]

Upvotes: 1

Views: 82

Answers (2)

Mayowa Ayodele
Mayowa Ayodele

Reputation: 559

I believe you only need an extra square bracket around your first for loop as shown below, let me know if this works.

year_diff = [[(1-(np.absolute(x-y)/2005)) for x in excluded_books_over10['yearOfPublication']] for y in years]

Upvotes: 0

Swazy
Swazy

Reputation: 398

This should produce the output you are after:

year_diff = [[(1-(np.absolute(x-y)/2005)) for y in years] for x in excluded_books_over10['yearOfPublication']]

Upvotes: 1

Related Questions