Python 用于计算元素的嵌套while循环有什么问题
我只想计算出F的每个元素在N中出现的频率,然后打印出来。我使用了嵌套for循环,它可以工作。但当我使用嵌套的while循环时,它并没有像预期的那样工作。我检查了代码,但找不到原因Python 用于计算元素的嵌套while循环有什么问题,python,python-3.x,Python,Python 3.x,我只想计算出F的每个元素在N中出现的频率,然后打印出来。我使用了嵌套for循环,它可以工作。但当我使用嵌套的while循环时,它并没有像预期的那样工作。我检查了代码,但找不到原因 F = [4,7,2] N = [2,3,4,2,5,6,3,2,6,7,3,4] 嵌套循环版本,按预期工作: four_count = 0 seven_count = 0 two_count = 0 for n in N: for f in F: if n == f and f == 4:
F = [4,7,2]
N = [2,3,4,2,5,6,3,2,6,7,3,4]
嵌套循环版本,按预期工作:
four_count = 0
seven_count = 0
two_count = 0
for n in N:
for f in F:
if n == f and f == 4:
four_count += 1
elif n == f and f == 7:
seven_count += 1
elif n == f and f == 2:
two_count += 1
print(str(F[0]) + " occurs in N " + str(four_count) + " times")
print(str(F[1]) + " occurs in N " + str(seven_count) + " times")
print(str(F[2]) + " occurs in N " + str(two_count) + " times")
4 occurs in N 2 times
7 occurs in N 1 times
2 occurs in N 3 times
这是正确的输出:
four_count = 0
seven_count = 0
two_count = 0
for n in N:
for f in F:
if n == f and f == 4:
four_count += 1
elif n == f and f == 7:
seven_count += 1
elif n == f and f == 2:
two_count += 1
print(str(F[0]) + " occurs in N " + str(four_count) + " times")
print(str(F[1]) + " occurs in N " + str(seven_count) + " times")
print(str(F[2]) + " occurs in N " + str(two_count) + " times")
4 occurs in N 2 times
7 occurs in N 1 times
2 occurs in N 3 times
嵌套while循环版本,输出错误:
four_count = 0
seven_count = 0
two_count = 0
N_Count = 0
F_Count = 0
while N_Count < len(N):
while F_Count < len(F):
if N[N_Count] == F[F_Count] and F[F_Count] == 4:
four_count += 1
elif N[N_Count] == F[F_Count] and F[F_Count] == 7:
seven_count += 1
elif N[N_Count] == F[F_Count] and F[F_Count] == 2:
two_count += 1
F_Count += 1
N_Count += 1
print(str(F[0]) + " occurs in N " + str(four_count) + " times")
print(str(F[1]) + " occurs in N " + str(seven_count) + " times")
print(str(F[2]) + " occurs in N " + str(two_count) + " times")
当N\u Count
之后重置F\u Count=0
,否则listF
只循环一次。因此,这将是:
...
while N_Count < len(N):
F_Count = 0
while F_Count < len(F):
...
或者类似的当N\u Count
时,您必须在之后重置F\u Count=0
,否则listF
只循环一次。因此,这将是:
...
while N_Count < len(N):
F_Count = 0
while F_Count < len(F):
...
或者类似的你是对的。谢谢你救了我一天。“在while N_Count