【问题标题】:For loop: Store items in list, then count and print numbers of items in that listFor循环:将项目存储在列表中,然后计算并打印该列表中的项目数
【发布时间】:2020-01-19 21:58:14
【问题描述】:

尝试从 Reddit API 计算项目,并将它们全部添加到列表中,然后打印所述列表中的行数。

所以,我尝试了一些方法,但到目前为止都没有成功。为什么这计数不正确,并在“redditqueue”中打印项目数量?欢迎任何帮助/建议!

x = []
for item in redditqueue: #redditqueue is a placeholder
    x.append(item)
    Count = x.count()
    print(Count)

如果redditqueue中有2个项目,我想要代码打印2,但它只是打印以下内容:

0
0

【问题讨论】:

    标签: python bots discord reddit praw


    【解决方案1】:

    如果您想知道redditqueue 中有多少项目,那么只需获取列表长度:

    print(len(redditqueue))
    

    如果redditqueue 是某种迭代器或生成器,则列出其整个序列并取其长度。

    print len(list(redditqueue))
    

    如果这太长了,并且您需要计算列表中项目的数量,那么不要在另一个结构中累积元素......只需 count

    for count, item in enumerate(redditqueue):
        pass
    
    print(count)
    

    【讨论】:

      【解决方案2】:

      len() 是你想要的。试试这个:

      x = []
      for item in redditqueue:
          x.append(item)
          print(len(x))
      

      【讨论】:

      • 啊,非常感谢,我想到了 len 但反对它。自从我使用 python 以来已经有一段时间了,我有一种误解,即 len() 只是计算字符的数量 - 但从外观上看,列表并非如此。
      • 对,len() 将计算字符串中的字符和列表中的项目。
      • len 返回任何可迭代项中的项目数。对于字符串,它是字符数。对于列表,它是元素的数量。对于dicts,它是键的数量。等等……
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-15
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      • 2016-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多