我希望在遍历它时通过子字符串获取列表中的元素。
例如,在以下示例列表中,我希望将"pass1"
,"pass2"
匹配元素和"pass3"
作为不匹配的元素。这是列表的简化版本,因为我需要遍历长列表。
请告诉我,在以下示例中我做错了什么。
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
答案 0 :(得分:1)
您不能对子字符串使用in
成员资格测试;您必须再次循环keyList
以测试每个子字符串。
通过前缀将所有字符串组合起来效率要高得多:
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])
这只打印匹配元素;所有其他键都是那些不匹配的键,但它们会自行打印:
>>> 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']