如何计算列表中的对象连续出现N次的次数?

时间:2018-10-01 10:39:49

标签: python-3.x

因此,我在这里所做的是,我正在生成1000次抛硬币,并将这些抛物列在列表中。然后,我试图做的是发现头被连续扔了3次,或者尾巴被连续扔了3次。我的尝试:

toss_count = 0
trips_count = 0
coin_tosses = []
while toss_count < 1000:
    toss = random.randint(1, 2)
    if toss == 1:
        coin_tosses.append("heads")
        toss_count += 1
    elif toss == 2:
        coin_tosses.append("tails")
        toss_count += 1

直到现在代码在执行我想要的操作。我的问题出在我接下来要做的事情上:

for trips in coin_tosses:
    if "'heads', 'heads', 'heads'" in coin_tosses:
        trips_count += 1
print(trips_count)

类似的事情显然是行不通的,但是我不知道该如何实现我在这里想要实现的目标。

3 个答案:

答案 0 :(得分:1)

您可以使用以下代码对其中的每个项目进行切片,将每个项目coin_tosses[counter:counter+3]占用三项

toss_count = 0
trips_count = 0
coin_tosses = []
while toss_count < 1000:
    toss = random.randint(1, 2)
    if toss == 1:
        coin_tosses.append("heads")
        toss_count += 1
    elif toss == 2:
        coin_tosses.append("tails")
        toss_count += 1

print(coin_tosses)

counter = 0
for trips in coin_tosses:
    if ['heads', 'heads', 'heads'] == coin_tosses[counter:counter+3]:
        trips_count += 1
    counter +=1

print(trips_count)

答案 1 :(得分:0)

我要遍历,检查值是否与前两个相同。我认为这应该有效。它计算三元组的总数,而不管它们是正面还是反面,您的代码似乎暗示这是您追求的。如果需要单独使用,可以轻松添加支票。

trips_count = 0
previous_value = None
value_before_that = None
for current_value in coin_tosses:
    if (current_value == previous_value) and (current_value == value_before_that):
        trips_count += 1
    value_before_that = previous_value
    previous_value = current_value

答案 2 :(得分:0)

您可以尝试以下操作:

import random
toss_count = 0
trips_count = 0
coin_tosses = []
while toss_count < 1000:
    toss = random.randint(1, 2)
    if toss == 1:
        coin_tosses.append("heads")
        toss_count += 1
    elif toss == 2:
        coin_tosses.append("tails")
        toss_count += 1

for i in range(len(coin_tosses)-2):
    if coin_tosses[i] == coin_tosses[i+1] == coin_tosses[i+2]:
        trips_count += 1

print(trips_count)