简体   繁体   English

如何创建collections.Counter列表?

[英]How to create list of collections.Counter?

I have a for loop and each time I call a function within each iteration, and the return of that functions is from type " collections.Counter ", and I would like at the end of the loop that lst will contain all collection.Counter 我有一个for循环,每次在每次迭代中调用一个函数时,该函数的返回都是从类型“ collections.Counter”返回的,我希望在循环结束时lst将包含所有collection.Counter

for gram in range(0, nGram):
   lst[gram]=getCollection(gram)

For a list , you need to use .append() : 对于列表 ,您需要使用.append()

for gram in range(nGram):
   lst.append(getCollection(gram))

You can turn that into a list comprehension: 您可以将其转换为列表理解:

lst = [getCollection(gram) for gram in range(nGram)]

您可以按照其他人的建议使用列表的append方法,也可以在此处简单地使用列表理解

lst = [getCollection(gram) for gram in range(nGram)]

Try to append it: 尝试附加它:

lst.append(getCollection(gram))

Otherwise (if gram is not a valid index of the list) you will end up with an IndexError, telling you that the list does not have that many elements—yet. 否则(如果gram不是列表的有效索引),您将最终得到IndexError,告诉您列表还没有那么多元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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