首页 > 解决方案 > 使用两个嵌套的 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}

标签: pythonpython-3.xnested-loops

解决方案


这是一个带有嵌套 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))+'}')

推荐阅读