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

时间:2015-08-31 08:26:40

标签: python nested-loops

我正在尝试检查列表的两个参数是否具有相同的数字,如果是,那么它们中有多少是相同的。我想使用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出现三次,依此类推......

1 个答案:

答案 0 :(得分:2)

您对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

符合要求。