Python检测字符串中的两个相同的东西

时间:2015-06-23 05:53:18

标签: python

while testcount < 100:  
   num1=randint(0,10)
   num2=randint(0,10)
   num3=randint(0,10)
   num4=randint(0,10)
   num5=randint(0,10)
   numo=[num1,num2,num3,num4,num5]

   if #there are two 7s# in numo:
      testcount=testcount+1
      num_of_successes=num_of_successes+1
   else:
      testcount=testcount+1

    print(num_of_successes,"out of 100 there were two 7s")

我如何检测&#39; numo&#39;中是否有两个7? 即使它没有使用大部分代码。

5 个答案:

答案 0 :(得分:5)

对于列表,您可以使用count()函数查找列表中是否存在传递给count函数的parameter元素。

示例 -

>>> l = [1,2,3,4,5,6,4]
>>> l.count(4)
2

答案 1 :(得分:1)

您可以通过在没有任何列表的情况下快速计数来避免搜索列表中的项目:

from random import randint

num_of_successes = 0

for testcount in xrange(100):
    if sum(int(randint(0, 10) == 7) for i in xrange(5)) == 2:
       num_of_successes += 1

print(num_of_successes, "out of 100 there were two 7s")

答案 2 :(得分:0)

您可以使用list.count()方法检查出现情况。

while testcount < 100:  
       num1=randint(0,10)
       num2=randint(0,10)
       num3=randint(0,10)
       num4=randint(0,10)
       num5=randint(0,10)

   numo=[num1,num2,num3,num4,num5]


   num_of_successes=numo.count(7)

   if num_of_successe == 2 : 
     print(num_of_successes,"out of 100 there were two 7s")

答案 3 :(得分:0)

for testcount in range(100):
   num1=randint(0,10)
   num2=randint(0,10)
   num3=randint(0,10)
   num4=randint(0,10)
   num5=randint(0,10)
   numo=[num1,num2,num3,num4,num5]

   if numo.count(7) == 2:
      num_of_successes=num_of_successes+1

print(num_of_successes, " out of 100 there were two 7s")

答案 4 :(得分:0)

我认为:

from random import randint
testcount = 0
num_of_successes = 0
while testcount < 100:
    num1 = randint(0, 10)
    num2 = randint(0, 10)
    num3 = randint(0, 10)
    num4 = randint(0, 10)
    num5 = randint(0, 10)
    numo = [num1, num2, num3, num4, num5]
    if numo.count(7) == 2:
        num_of_successes += 1
    testcount += 1
print num_of_successes, "out of 100 there were two 7s"