# - 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

``````

``````
counter = [0] * 10

for x in l_one:

counter[x] ++

for x in l_two:

if counter[x] > 0:

counter[x] --

``````
``````
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)

``````

``````
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}

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)

``````

``````
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

``````