user9176398
user9176398

Reputation: 471

for loop to list comprehension

i would like to turn this for loop into list comprehension

people_metrics = []
for idx, user_id in tqdm(enumerate(list(interactions_test_indexed_df.index.unique().values))):
        anime_user_metrics = evaluate_model_for_anime_watcher(model, user_id)  
        anime_user_metrics['_user_id'] = user_id
        people_metrics.append(anime_user_metrics)
    print('%d users processed' % idx)

enumerate looks like

idx user_id
0      20
1      32
...etc

i tried :

    anime_user_metrics = [evaluate_model_for_anime_watcher(model, user_id) for idx, user_id in tqdm(np.ndenumerate(list(interactions_test_indexed_df.index.unique().values)))]

it work. then i tried :

anime_user_metrics['_user_id']  = list(zip(*enumerate(interactions_test_indexed_df.index.unique().values)))[::-1]

or

user_proxy = [b for a, b in np.ndenumerate(list(interactions_test_indexed_df.index.unique().values))]
anime_user_metrics['_user_id'] = user_proxy

but when i'm tried to do the 2nd line i got an error TypeError: list indices must be integers, not str

Upvotes: 0

Views: 329

Answers (1)

joel
joel

Reputation: 7868

I wouldn't necessarily recommend this because it may be considered hard to read, but one way is to use dict unpacking with **

v = tqdm(enumerate(list(interactions_test_indexed_df.index.unique().values)))
people_metrics = [
    {**evaluate_model_for_anime_watcher(model, user_id), '_user_id': user_id}
    for idx, user_id in v
]

a for loop might just be better in this case

and yes, in your attempt, you define a list anime_user_metrics (it's a list because the comprehension is surrounded by []), then try to access values of it by indexing with a string. Lists index with integers. Hence list indices must be integers, not str

Upvotes: 1

Related Questions