【问题标题】:while loop to count occur times [closed]while循环计算发生次数[关闭]
【发布时间】:2017-04-03 19:16:06
【问题描述】:

我有两个列表FN,我需要使用while 循环函数来计算F 的每个元素在N 中出现的频率。这是我的清单:

F = [4,7,2] 
N = [2,5,4,2,5,9,3,2,3,7,3,4]

我希望得到这样的结果:

4 occurs in N 2 times
7 occurs in N 1 times
2 occurs in N 3 times

这是我的代码:

index = 0
while index < len(N):
    value = N[index]
    print (value)
    index = index +1
else:
     print(index, "occurs in N", value, "times")
print()

有什么建议吗?

【问题讨论】:

  • 您需要使用 if 语句来查看何时 N(index) == F 的元素并计算该 if 语句为 True 的次数。

标签: python python-3.x while-loop counter


【解决方案1】:

您可以简单地使用Counter,然后使用使用查找:

from collections import Counter

ncount = Counter(N)

for f in F:
    print(f,"occurs in N",ncount[f],"times")

这将导致时间复杂度 O(|F|+|N|)(给定字典查找发生在 O(1) 中,几乎总是这样)。

你可以将for循环变成while循环,如下:

i = 0
while i < len(F):
    f = F[i]
    print(f,"occurs in N",ncount[f],"times")
    i += 1

但最好使用for 循环,因为for 循环进程等是有保证的(例如,您不必考虑递增i)。

鉴于您不允许使用 Counter,您可以自己进行计数,例如使用列表推导:

i = 0
while i < len(F):
    f = F[i]
    print(f,"occurs in N",len([1 for x in N if x == f]),"times")

或使用sum:

i = 0
while i < len(F):
    f = F[i]
    print(f,"occurs in N",sum(x == f for x in N),"times")

或者你可以使用列表的.count()函数:

i = 0
while i < len(F):
    f = F[i]
    print(f,"occurs in N",N.count(f),"times")

【讨论】:

  • 感谢@WIllem Van Onsem,但我们需要使用while 循环而不是for 循环。我被困在如何使用while循环来编写代码......
  • @Sophie:你可以使用Counter吗?
  • 我们不允许使用计数器,这就是为什么我对这个问题如此困惑?
【解决方案2】:
f = [4, 7, 2]
n = [2, 5, 4, 2, 5, 9, 3, 7, 3, 4]

index1 = 0

while index1 < len(f):
    value = f[index1]
    count = 0
    index2 = 0
    while index2 < len(n):
        if n[index2] == value:
            count += 1
        index2 += 1
    print(value, "occurs in N", count, "times")
    index1 += 1

这是一个只有while循环的解决方案,我会使用上面答案中的计数器。为什么需要使用while循环?

【讨论】:

  • 为什么要使用第二个while循环而不是n.count(value)
  • 据我了解她的问题,她只被允许使用 while 循环,n.count(value) 确实会更好。 @教授
猜你喜欢
  • 2016-12-01
  • 1970-01-01
  • 2019-01-18
  • 2017-07-23
  • 1970-01-01
  • 2012-03-23
  • 1970-01-01
  • 2011-09-29
  • 2016-06-25
相关资源
最近更新 更多