简体   繁体   中英

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']]

这应该会产生您所追求的输出:

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

我相信你只需要一个额外的方括号围绕你的第一个 for 循环,如下所示,让我知道这是否有效。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM