python - 使用两个嵌套的 for 循环打印两个列表的公共元素
问题描述
我是 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}
解决方案
这是一个带有嵌套 for 循环的代码,它保留重复的值。
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:
for j in sequenceTwo:
if (i==j):
listOfIntersection.append(i)
print('The intersection of these two sets is {' +(", ".join(str(i) for i in listOfIntersection))+'}')
这是第二种解决方案,它完全模仿了您首先所做的事情:
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:
for j in sequenceTwo:
if (i==j):
listOfIntersection.append(i)
sequenceTwo.remove(i)
break
print('The intersection of these two sets is {' +(", ".join(str(i) for i in listOfIntersection))+'}')
推荐阅读
- javascript - 无法使用 Bootstrap 折叠
- javascript - Vue 模板使用 JavaScript 内置函数
- powershell - Powershell Where-Object 返回 null
- typescript - 如何缩小 Firestore 字段值
- jquery - 依次切换类
- python - 使用 AIRSIM 和 python API 移动turtlebot3
- c# - Blazor - 提交表单而不重新加载(没有 JS)
- google-chrome - Google Chrome 更新 - 从 Inspector CSS 复制代码的问题
- node.js - 如何在 Web 应用程序中集成免费广播服务
- apache-spark - elasticsearch返回要触发的对象的空列表