简体   繁体   中英

Removing the rows that contain the same value in python

I want to combine the elements in list_a and list_b. Both list_a and list_b have the same elements.There are 5 elements in each list so the output should have 5x5=25. But I want my program not to print those 5 lines which have same elements.Please have a look at output.

list_a=["apple","banana","melon","grape","orange"] list_b=["apple","banana","melon","grape","orange"]
for x in list_a: for z in list_b: print(x,"-",z)

apple-apple banana-banana melon-melon grape-grape orange-orange Thank you

I think you are looking for a cartesian product with no duplicate rows.

If so:

>>> ['{} - {}'.format(a,b) for a in list_a for b in list_b if a!=b]
['apple - banana', 'apple - melon', 'apple - grape', 'apple - orange', 'banana - apple', 'banana - melon', 'banana - grape', 'banana - orange', 'melon - apple', 'melon - banana', 'melon - grape', 'melon - orange', 'grape - apple', 'grape - banana', 'grape - melon', 'grape - orange', 'orange - apple', 'orange - banana', 'orange - melon', 'orange - grape']

Or, on Python 3.7:

>>> [f'{a} - {b}' for a in list_a for b in list_b if a!=b]

To make your version work, just add a continue in your loop:

for x in list_a:
    for z in list_b:
        if x==z: continue
        print(x,"-",z)

Or,

for x in list_a:
    for z in list_b:
        if x!=z: print(x,"-",z)

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