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
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] 삭제
몇 마디 만하겠습니다