check for multiple substring match in a list while iterating list

Mr Damsal

I want to get the elements in a list that match by substring while iterating over it. For instance, in following example list, i want to get "pass1", "pass2" matching elements and "pass3" as element that doesn't match. This is a simplified version of the list, as I need to iterate over the long list.

Please, let me know, what am I doing wrong in the following example.

keyList=["pass1_v1","pass1_v3","pass1_v5","pass2_v1","pass2_v3","pass3_v4"]
for x in keyList:
    match=x.rsplit("_",1)[0] ## splitting the list elements seperated by "_"..eg:- pass1 to check how many elements match
    if  match in keyList:
        print("matching are %s" %x) ## expecting to print eg:-pass1_v1 and pass1_v3
    else :
        print ("non matching are %s"%x)     # expecting to print pass3_v4
Martijn Pieters

You cannot use in membership testing with a substring; you'd have to loop over keyList again to test each substring.

It'd be far more efficient to grou all strings by prefix:

by_prefix = {}
for x in keyList:
    by_prefix.setdefault(x.rsplit('_', 1)[0], []).append(x)

for prefix, matches in by_prefix.iteritems():
    print 'Matches for {} are {}'.format(prefix, by_prefix[prefix])

This only prints the matching elements; all other keys are those that didn't match, but they'll be printed on their own:

>>> keyList = ["pass1_v1", "pass1_v3", "pass1_v5", "pass2_v1", "pass2_v3", "pass3_v4"]
>>> by_prefix = {}
>>> for x in keyList:
...     by_prefix.setdefault(x.rsplit('_', 1)[0], []).append(x)
... 
>>> for prefix, matches in by_prefix.iteritems():
...     print 'Matches for {} are {}'.format(prefix, by_prefix[prefix])
... 
Matches for pass2 are ['pass2_v1', 'pass2_v3']
Matches for pass1 are ['pass1_v1', 'pass1_v3', 'pass1_v5']
Matches for pass3 are ['pass3_v4']

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Check whether a list starts with the elements of another list

Check if a list has one or more strings that match a regex

Kotlin find substring in list of strings

Is it correct to append to a list while iterating over it?

Match multiple fields in a list?

Splitting and sorting a list based on substring

Iterating through a list and querying a value

Iterating through a list of a class

ansible check max number list

Issue while recoding multiple variables, error - in .subset(x, j) : invalid subscript type 'list'

Check list overlap with list comprehensions

Issue while recoding multiple variables, error - in .subset(x, j) : invalid subscript type 'list'

List of servers to check for SSH availability

Django template not iterating through list

List Object with multiple "keys" in it

C # 구분 List <string> by substring

Using a list in multiple Functions

Delete folders which not match a list

How to iterate through a list and while iterating, iterate through another list and replace values for upper list with inner list key value pairs

Iterating a generic list with super keyword

Clojure Iterating over a list of hash maps

Iterating through subelements of a list

Check empty vector in initializer list

Print multiple fields based on partial substring match inside one of the fields

RegEx to match list

NameError when searching for substring in Python list

Sort items in list by index of a substring in another list

Check if values in a list exisiting in another list

Python - Error , iterating list of dictionaries

TOP 리스트

뜨겁다태그

보관