简体   繁体   English

包含用于比较两个列表中元素的操作

[英]Contains operation for comparing elements in two lists

How can I compare two strings for contains operation? 如何比较包含操作的两个字符串? I tried using the in operator without success 我尝试使用in运算符没有成功

list_1=['check value 1','check value 2']

list_2=['12312 check value 1 ','234 check value 2']

for ele in list_1:
    if ele in list_2:
        print 'element present'
    else:
        print 'abscent'

Result 结果

abscent
abscent

I know we can compare them using another loop in list_2 and in over all elements. 我知道我们可以用另一个循环中list_2 对所有元素进行比较。 I am curious whether there is a better approach. 我很好奇是否有更好的方法。

You'll need to test against every element in list_2 ; 您需要针对list_2中的每个元素进行list_2 using membership on lists requires that the whole string is present in the list. 在列表上使用成员资格要求整个字符串都在列​​表中。

for partial in list_1:
    if any(partial in value for value in list_2):
        print 'element present'
    else:
        print 'absent'

Here the any() function , combined with a generator expression, at least stops searching as soon as a match has been found. 在这里, any()函数与生成器表达式组合在一起,至少在找到匹配项后立即停止搜索。

Your code needed just a little change :-) 您的代码只需要一点更改:-)

list_1=['check value 1','check value 2']

list_2=['12312 check value 1 ','234 check value 2']

for ele in list_1:
    for list2_ele in list_2:
        if ele in list2_ele:
            print 'element present'
        else:
            print 'absent'

You just needed the second for loop :-) 您只需要第二个for循环即可:-)

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

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