简体   繁体   English

如何在Python中比较列表元素

[英]How to compare the list elements in Python

Here i am having two lists : 在这里,我有两个列表:

list1 = ['2C535EB58F19B58' , '7B89D9071EB531B143594FF909BAC846' , '0509']

list2 = ['1641AB0C9C5B8867' , '0098968C' , '509']

I need to compare the elements inside list2 with list1 elements. 我需要将list2内的元素与list1元素进行比较。

I want the output to be , after comparing : 比较后,我希望输出是:

509

since 509 is present in 0509. 因为0509中存在509。

How can i achieve so ? 我怎样才能做到这一点? Does regex can help me in this ? 正则表达式可以帮助我吗?

Try this: Here we are checking whether element in list2 is a substring of an element in list1. 试试看:在这里,我们检查list2中的元素是否是list1中元素的子字符串。

list1 = ['2C535EB58F19B58' , '7B89D9071EB531B143594FF909BAC846' , '0509']

list2 = ['1641AB0C9C5B8867' , '0098968C' , '509']

for i, j in zip(list1, list2):
    if j in i:
        print(j)

One-liner which will append to a list: 单线将附加到列表中:

print( [j for i, j in zip(list1, list2) if j in i])

There could be more simple and better answers. 可能会有更简单更好的答案。 If it helps, you can opt it. 如果有帮助,您可以选择它。

You can do something like this: 您可以执行以下操作:

common_elements = []
for x in list1:
    for y in list2:
        if y in x:
            common_elements.append(y)

common_elements will contain the elements you need. common_elements将包含您需要的元素。

As already proposed by BearBrown in a comment, there is an easy way to achieve your goal. 正如BearBrown在评论中已经提出的那样,有一种简单的方法可以实现您的目标。 There is no reason to think about regular expressions at all (the in -operator is powerful enough). 没有理由去想在所有的正则表达式(在in -运算符是足够强大)。

[x for x in list2 if any(y for y in list1 if x in y)]

Here you are looking for each string x in list2 if it is a substring of any string y in list1 and finally save each matching substring x in a new list. 在这里,您要在list2中查找每个字符串x (如果它是list1中任何字符串y的子字符串),最后将每个匹配的子字符串x保存到新列表中。

for x in list2:
    for y in list1:
        if x in y:
            print x #or whatever

nested for-loops, I think this is a simple way, but I'm sure there is a better one 嵌套的for循环,我认为这是一种简单的方法,但是我敢肯定有更好的方法

You can simply use in operation in python to check whether one string is in another string. 您可以简单地在python中使用in operation来检查一个字符串是否在另一字符串中。

The easiest way to solve your problem would be 解决问题的最简单方法是

[y for y in list2 if any(y in x for x in list1)]

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

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