【问题标题】:Creating two lists and compare the matching [closed]创建两个列表并比较匹配的[关闭]
【发布时间】:2014-10-23 06:27:31
【问题描述】:

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

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

【问题讨论】:

  • 你的代码演示了什么?
  • 请更清楚地定义您的问题。我猜你知道如何创建第二个列表(随机数?) - 你想知道如何找出两个列表之间是否有重复项吗?如果是这样,这些重复项是否必须位于同一位置,或者您是否认为[1,2,3,4] 和[4,3,2,1] 完全重复?

标签: python string output


【解决方案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

【讨论】:

  • 它返回 AttributeError: 'list' object has no attribute 'intersection'
  • @Turner 设置 != 列表。您可以将列表转换为集合(就像我在上面的示例中所做的那样)。
  • 抱歉,我不太理解您的回复。 '导入随机matches_a= random.sample(range(1, 20), 5) matches_b= random.sample(range(1, 20), 5) print matches_a.intersection(matches_b) print matches_a & matches_b'
  • @Turner 我更新了我的答案。
【解决方案2】:

列表理解单行:

[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]

【讨论】:

  • 这只是返回最高匹配而不是全部...
  • 应该可以...发布您的整个代码并让我们看看。
【解决方案3】:

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

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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2020-07-06
    • 1970-01-01
    相关资源
    最近更新 更多