检查列表的两个值是否具有相同的数字 return 有多少相同

check if two values of lists have the same numbers return how many are same

我正在尝试检查列表的两个参数是否具有相同的数字,如果是,有多少是相同的。我想使用 for 循环来执行此操作。

到目前为止我已经试过了,但它不起作用。

num_1 = get_how_many_match(2, [5, 2, 2, 5, 2]) num_2 = get_how_many_match(5, [5, 2, 2, 5, 2]) num_3 = get_how_many_match(4, [5, 2, 2, 5, 2]) num_4 = get_how_many_match(3, [5, 3, 4, 3, 3]) num_5 = get_how_many_match(6, [5, 2, 2, 6, 2])

def get_how_many_match(value_to_match, list_of_dice):
list = [0]

for num in list_of_dice:
    if value_to_match in list_of_dice:
        value_to_match == num
        a = len(str(num))
        list = num

return list

我得到的输出是:

2 2 [0] 3 2

但我想要的输出是:

3 2 0 3 1

因为在num_1中,数字2出现了3次,以此类推...

您对 get_how_many_match 的定义完全不正确。考虑这会产生所需的结果:

>>> def get_how_many_match(value_to_match, list_of_dice):
...     return list_of_dice.count(value_to_match)
... 
>>> num_1 = get_how_many_match(2, [5, 2, 2, 5, 2]) 
>>> num_2 = get_how_many_match(5, [5, 2, 2, 5, 2]) 
>>> num_3 = get_how_many_match(4, [5, 2, 2, 5, 2]) 
>>> num_4 = get_how_many_match(3, [5, 3, 4, 3, 3]) 
>>> num_5 = get_how_many_match(6, [5, 2, 2, 6, 2])
>>> 
>>> print num_1, num_2, num_3, num_4, num_5
3 2 0 3 1

如果是这样,那么也许:

def get_how_many_match(value_to_match, list_of_dice):
    count = 0
    for dice in list_of_dice:
        if dice == value_to_match:
           count += 1
    return count

符合要求。