创建两个列表并比较匹配

时间:2014-10-23 06:27:31

标签: python string output

我有两个数字列表,但我需要进行评估,看看是否有任何数字匹配,然后输出匹配的数字。

import random
matches = random.sample (range(1, 20), 5),random.sample (range(1, 20), 5)

3 个答案:

答案 0 :(得分:1)

列表理解一个班轮:

[x for x in list_a if x in list_b]

您将获得两个列表中包含的项目列表。 演示所有项目:

>>> a = range(10,50)
>>> b = range(10,50)
>>> [x for x in a if x in b]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]

答案 1 :(得分:1)

您可以使用集合交集。

from random import sample

set_a = set(sample(range(0, 50), 10))
set_b = set(sample(range(0, 50), 10))

print set_a.intersection(set_b) # [3, 4]
print set_a & set_b # sugar for the same thing

答案 2 :(得分:0)

根据我对您的代码的理解,我想出了以下代码。如果这有助于你,请告诉我

m = [1,2,3]
n = [3,4,1]
for i in m:
    for j in n:
        if i == j:
            print "matched elements are list1 and list2 are (%s) and (%s)" %(i,j)
        else:
            print "list1 and list2 have unique elements"