[英]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 ...}
要么
return dict(...)
要么return {key: locs for ...}
The second version should be more pythonic and preferred for python 2.7 or 3.1+第二个版本应该更 pythonic 并且首选 python 2.7 或 3.1+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.