【问题标题】:Is there a way to get the number of items I print as a result of a FOR cycle in Python?有没有办法获得我打印的项目数量作为 Python 中的 FOR 循环的结果?
【发布时间】:2021-03-08 19:08:03
【问题描述】:

我有这个代码:

C = 50000
threshold = 0.3
for i in range(1, 18598):
    if binned_orcs[i] > C and ori[i] > threshold: Origins = print(i)

然后我想有办法知道在打印这些条件的情况下循环有多少项目,但是因为每个来源都打印在不同的行上,所以我不能使用 len(Origins) 我想,有没有办法?

就像代码输出是:

1875
2550
3424
7426
7498
9065
9866
9924
11828
12116
12334
13317
13788
15110
15348
16988
17185
17572
18516

这是 19 个数字,我想要一个代码行,打印出来时只会给我 19。

【问题讨论】:

  • if 块内创建一个计数器以递增它?
  • 每次迭代后只需使用计数器和 +=1。打印计数器而不是打印的任何内容。
  • 顺便说一句,“Origins”总是“None”,因为 print() 总是返回“None”。
  • 我来这里是为了评论 Origins are None 的事情。我猜这是一个错字,而不是实际的变量分配(如果打印实际上是临时的)。否则,您可能最好在那里使用生成器,因为范围也非常适合内存(docs.python.org/3.8/library/stdtypes.html#ranges

标签: python python-3.x numpy string-length


【解决方案1】:

您可以添加一个计数器并自己跟踪号码:

count = 0
for i in range(1, 18598):
    if binned_orcs[i] > C and ori[i] > threshold:
        print(i)
        count += 1

print(count)

【讨论】:

    【解决方案2】:

    您也可以enumerate 结果并获取枚举函数的最后一个结果。这将通过在每个循环中覆盖计数器变量的值来工作,依赖于范围trick小心,因为这是我们在 python 中通常会避免的事情(您通常不会故意这样做)

    C = 50000
    threshold = 0.3
    
    for num, elem in enumerate(i for i in range(1, 18598)
                               if binned_orcs[i] > C and ori[i] > threshold):
        print(elem)
    print(num + 1)
    

    请注意,我在最终总和中加了 1,因为它从 0 开始,我猜你的计数不会。否则删除它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多