简体   繁体   English

在python中删除包含相同值的行

[英]Removing the rows that contain the same value in python

I want to combine the elements in list_a and list_b. 我想组合list_a和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. list_a和list_b都具有相同的元素。每个列表中有5个元素,因此输出应为5x5 = 25。 But I want my program not to print those 5 lines which have same elements.Please have a look at output. 但是我希望我的程序不要打印出具有相同元素的那5行,请看一下输出。

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: 或者,在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: 要使您的版本正常工作,只需在循环中添加一个continue

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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