如何在列表中搜索2个相同的数字? (蟒蛇)

时间:2019-05-05 17:14:37

标签: python list

假设我的列表由n = [0,1,0,2,2,0,0]

组成
if 2 in n and 2 in n
print ("There are 2's")

elif 2 in n
print ("just one 2")

我如何使它在打印语句之前找到两个2,否则如果只是onw,它只会打印它

5 个答案:

答案 0 :(得分:2)

您可以只使用count中的list方法,

>>> n
[0, 1, 0, 2, 2, 0, 0]
>>> elm = 2
>>> print("There are {} {} in {}".format(n.count(elm), elm, n))
There are 2 2 in [0, 1, 0, 2, 2, 0, 0]

,或者,如果您无法使用list之类的count的任何方法,只需手动计数即可,

>>> print("There are {} {:d} in {}".format(len([1 for x in n if x == elm]), elm, n))
There are 2 2 in [0, 1, 0, 2, 2, 0, 0]

答案 1 :(得分:0)

使用count方法。

从文档中:https://docs.python.org/3/tutorial/datastructures.html

  

list.count(x)
  返回x出现在列表中的次数。

n = [0,1,0,2,2,0,0]
print(n.count(2))
#2

n = [0,1,0,1,2,0,0]
print(n.count(2))
#1

n = [0,1,0,1,1,0,0]
print(n.count(2))
#1
0

要编写自己的计数方法,只需遍历列表,然后在看到期望的数字时递增计数器

def count_n(li, num):

    c = 0
    #Iterate over the list using for loop
    for n in li:
        #If you see the number, increment the count
        if num == n:
            c+=1
    #Return count
    return c


print(count_n([0,1,0,2,2,0,0], 2))
#2
print(count_n([0,1,0,2,1,0,0], 2))
#1
print(count_n([0,1,0,1,1,0,0], 2))
#0
print(count_n([],2))
#0

答案 2 :(得分:0)

if n.count(2) == 2:
    print('There are 2 two`s')

没有列表方法:

c = 0
for number in n:
    if number == 2:
        c += 1
if c == 2:
    print('There are 2 two`s')

答案 3 :(得分:0)

from collections import defaultdict

dic = defaultdict(int)

n = [0,1,0,2,2,0,0]

for i in n:
    dic[i]+=1

element = 2
if element in dic.keys():
    print("frequency of {} in list is {}.".format(element, dic[element]))
else:
    print("element {} not present in list".format(element))

输出

frequency of 2 in list is 2.

答案 4 :(得分:0)

n = [0,1,0,2,2,0,0]
count=0 # counter

for item in n: # For loops iterate over a given sequence.
     if item == 2: # check if item is 2
          count += 1 # This is the same as count = count + 1

# if...else statement: Decision making is required when we want to execute a code only if a certain condition is satisfied.
if count>1:
     print ("There are 2's")
elif  count ==1:
     print ("just one 2")

n = [0,1,0,2,2,0,0]
count=0 # counter
# list comprehension
count = sum([1 for item in n if item == 2]) # Single Line For Loops
# expr1 if condition1 else expr2 if condition2 else expr
print ("There are 2's" if count >1 else "just one 2" if count == 1 else "") #ternary expression
  

三元运算符三元运算符在Python中通常被称为条件表达式。这些操作员评估一些东西   根据条件是否成立

     

语法: condition_if_true,如果条件为condition_if_false

     

使用这些条件表达式的示例:

is_nice = True
state = "nice" if is_nice else "not nice"
     

它允许快速测试条件而不是多行if语句。

  

列表理解

     

列表理解为创建列表提供了一种简洁的方法。

     

它由包含表达式的方括号和一个for组成   子句,则for或if子句为零或多个。

     

结果将是通过计算表达式得到的新列表   在其后的for和if子句的上下文中。

     

列表推导始终返回结果列表。如果你曾经   这样做:

new_list = []
for i in old_list:
    if filter(i):
        new_list.append(expressions(i))
     

您可以使用列表理解功能获得相同的结果:

new_list = [expression(i) for i in old_list if filter(i)]