- python - 通常,如何比较两个随机生成的列表以查找元素

我需要程序来比较列表以查找列表有多少相同的数字,但是,我不确定该如何实现。


import random



X = 0



while X<2000:



 House_deal = [random.randint(0,9) for House_deal in range(5)]


 Player_deal = [random.randint(0,9) for House_deal in range(5)]


 print("House numbers:", House_deal)


 print("Player numbers:", Player_deal)


 print("")


 X += 1



时间:

假设我们有两个随机生成的列表的l_onel_two


counter = [0] * 10


answer = 0


for x in l_one:


 counter[x] ++


for x in l_two:


 if counter[x] > 0:


 counter[x] --


 answer ++


print(answer)




import random


from collections import Counter



for _ in range(2000):


 House_deal = [random.randint(0,9) for _ in range(5)]


 Player_deal = [random.randint(0,9) for _ in range(5)]



 hc = Counter(House_deal)


 pc = Counter(Player_deal)


 common = hc.keys() & pc.keys() #get the intersection of both keys


 counts = 0


 for cel in common:


 counts += min(hc[cel], pc[cel])



 print("House numbers:", House_deal)


 print("Player numbers:", Player_deal)


 print("Common numbers:", counts)



我还将while循环更改为for循环。

你可以定义类似这里的函数,使用len()函数来获取列表中元素的数量,这些函数将列表设置为设置和获取它们的交叉点,这将是一些共同的元素,这样,如果你决定也要你还可以看到它们之间不共通的元素,或者你甚至可以修改此选项从另一个列表中减去一个列表以获得它们不共通的元素如这里,这里 ,如果这是你要找的,请告诉我。

可以按如下所示使用函数:


def compare(list1 , list2):



 common_list = []



 for i in list1:


 if i in list2:


 common_list.append(i)



print(len(common_list)) # Number of common elements



它能工作 :


import random


list_one = random.sample(range(9), 4)


list_two = random.sample(range(9), 4)


print(list_one)


print(list_two)


count = 0


for item_one in list_one:


 for item_two in list_two:


 if item_one == item_two:


 count +=1



print(count)




P:指令 for item_two in list_two: 可能改变 if item_one in list_two:

以前答案的变体。


counter_1 = {k, 0 : k in l_one}


counter_2 = {k, 0 : k in l_two}


answer = 0


for x in l_one:


 counter_1[x] = counter_1[x] + 1


for x in l_two:


 counter_2[x] = counter_2[x] + 1


for x, v1 in counter_1.items():


 v2 = counter_2.get(x, 0)


answer = answer + min (v1, v2)


print(answer)



你可以在python中使用set数据类型,并执行如下操作,


In [1]: from random import randint



In [2]: import random



In [3]: random.seed(123)



In [4]: x = set([randint(0,9) for x in range(5)])



In [5]: y = set([randint(0,9) for x in range(5)])



In [6]: x


Out[6]: {0, 1, 4, 6}



In [7]: y


Out[7]: {0, 1, 6, 8}



In [8]: cnt = len(x & y) # return the amount of numbers in common, e.g. {0, 1, 6}



In [9]: cnt


Out[9]: 3



希望它能帮上忙。

...