while循环计数发生次数

时间:2017-04-03 19:16:07

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

我有两个列表FN,我需要使用while循环函数来计算FN的每个元素出现的频率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()

这是我的代码:

questionNumbers = [1,2]
    questionChosen = random.choice(questionNumbers)
    if questionChosen == 1:
        del questionNumbers[questionNumbers.index(questionChosen)]
        q1 = "Who is John Von Neumann?"
        print(q1)

有什么建议吗?

2 个答案:

答案 0 :(得分:3)

您可以简单地使用Counter,然后使用use lookups:

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)。< / p>

鉴于您不允许使用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")

答案 1 :(得分:0)

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循环的解决方案,我会在上面的答案中使用一个Counter。为什么需要使用while循环?