【发布时间】:2021-03-20 12:38:50
【问题描述】:
我是 python 新手,我有这段代码可以打印出两个序列之间的交集。
代码运行良好,但我正在尝试将其转换为嵌套循环类型的代码。我尝试了很多东西,但都没有成功,你能帮帮我吗?
这里是代码
print("This program finds the common elements of two lists")
sequenceOne = input("Please enter the space-separated elements of the first list: ")
sequenceTwo = input("Please enter the space-separated elements of the second list: ")
sequenceOne = sequenceOne.split()
sequenceTwo = sequenceTwo.split()
listOfIntersection = []
for i in sequenceOne:
if i in sequenceTwo:
sequenceTwo.remove(i)
listOfIntersection.append(i)
print('The intersection of these two lists is {' +(", ".join(str(i) for i in listOfIntersection))+'}')
输出:
This program finds the intersection of two sets
Please enter the space-separated elements of the first set: 12 k e 34 1.5 12 hi 12 0.2
Please enter the space-separated elements of the second set: 1.5 hi 12 0.1 54 12 hi hi hi
The intersection of these two sets is {12, 1.5, 12, hi}
【问题讨论】:
-
检查我的新答案,这是你想要的吗?
-
如果可行,最好不要尝试使用嵌套循环。使用 set(...) 提出的答案是使用 Python 处理此问题的非常好且简单/更好的方法。
-
@Malo 我知道这更干净,但它是一个分配,它是关于嵌套循环的????
-
@MMSS19 您应该编辑并说明这一点。简单的方法是将“if i in sequenceTwo:”替换为第二个 for 循环“for j in sequenceTwo:” ...
-
输出真的很奇怪,你如何定义是否需要保留重复项?我在第一组中数 3x12,在第二组中数 4x'hi',但答案有 2x 12 和 1x hi .. 你能解释一下吗?
标签: python python-3.x nested-loops