简体   繁体   中英

Prevent getting a generator object

Considering the following function:

from collections import defaultdict

def duplicate_checker(word_list):
    word_dict = defaultdict(list)

    for i,item in enumerate(tweet_list):
        word_dict[item].append(i)

    return ((key, locs)  for key, locs in word_dict.items() if len(locs) >= 1)

When I call the function with a list of words, it should check for duplicates and return a dictionary that contains the words in the list as keys, and as value a list of their positions in the list of words that was used as an argument to call the function.

However when I want to print the results it returns this:

<generator object <genexpr> at 0x02E306C0>

How can I make it return the dict as I described above?

Either return dict(...) or return {key: locs for ...}

The second version should be more pythonic and preferred for python 2.7 or 3.1+

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