【问题标题】:program finds the intersection of two sets [duplicate]程序找到两组的交集[重复]
【发布时间】:2021-03-15 17:57:26
【问题描述】:

我正在尝试编写一个程序来查找两个序列的交集。

然后程序会生成两个序列交集的所有元素的列表(以任何顺序),同时考虑到值的复制。这意味着如果一个值 'i' 在第一个序列中出现两次,在第二个序列中出现 3 次,那么交集应该包含两个 'I' 实例

这是我的代码:

print("This program finds the intersection of two sets")

sequenceOne = input("Please enter the space-separated elements of the first set: ")
sequenceTwo = input("Please enter the space-separated elements of the second set: ")

sequenceOne = sequenceOne.split()
sequenceTwo = sequenceTwo.split()
listOfIntersection = []

for i in sequenceOne:
     if i in sequenceTwo:
        listOfIntersection.append(i)

print(listOfIntersection)

输入:

sequence One: 12 k e 34 1.5 12 hi 12 0.2
sequence Two:1.5 hi 12 0.1 54 12 hi hi hi 

我的输出:

['12', '1.5', '12', 'hi', '12']

期望的输出:

{12, 12, 1.5, hi}

我如何只获得两个序列中出现的数字,即使它的数字相同? (我希望这是有道理的)。 还有如何获得大括号?

谢谢。

【问题讨论】:

  • @mr_mooo_cow 是的,但我得到 [] 作为输出而不是 {}。我该如何应对?
  • Python 中的花括号用于字典和集合。字典使用一个键:值对所以不是你想要的,但是一个集合不包括重复项。你能解释一下你想要做什么,你需要花括号吗?
  • @mr_mooo_cow 是作业,作业中说要严格遵守格式。示例的输出用花括号给出,所以我需要它像我猜的那样。
  • @mr_mooo_cow 没关系,花括号只是一个随机输入,而输出不是一个集合。不过真的谢谢你的帮助,我能写代码了

标签: python python-3.x loops input


【解决方案1】:
from collections import Counter

c = list((Counter(a) & Counter(b)).elements())

来自答案:Intersection of two lists including duplicates?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-12
    • 2015-12-23
    • 2017-12-29
    • 2013-07-25
    • 2013-01-14
    • 2017-01-04
    • 1970-01-01
    • 2021-01-02
    相关资源
    最近更新 更多