简体   繁体   中英

How to select pairs from two lists/?

I have two lists from which I want to select pairs in such a way that each item in one set is paired with another item in the other set only when they are not the same. This is the code I tried so far.

start1 = [1, 4, 0, 2, 0, 3, 3, 3, 3, 1]
end1 = [0, 0, 0, 2, 1, 2, 2, 4, 1, 4]

for x in start1:
    for y in end1:
        if x != y:
            print(x,y)

The above code gives me results that look like this...

1 0
1 0
1 0
1 2
1 2
1 2
1 4
1 4
4 0
4 0
4 0
4 2
4 1
4 2
4 2
4 1
.
.
.

However, trying to get results like this...

1 0
4 0
0 1
3 2
3 2
3 4
3 1
1 4

As I am new to python, I am having difficulties with this problem. Can someone kindly guide me to achieve my goal?

Regards.

Zip the lists together, filtering the results.

start1 = [1, 4, 0, 2, 0, 3, 3, 3, 3, 1]
end1 = [0, 0, 0, 2, 1, 2, 2, 4, 1, 4]

for x, y in zip(start1, end1):
    if x != y:
        print(x,y)
[item for item in zip(start1, end1) if item[0] != item[1]]
>> [(1, 0), (4, 0), (0, 1), (3, 2), (3, 2), (3, 4), (3, 1), (1, 4)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM