我有以下列表_A:
['0', '1', '2', '3', '4', '5', '6', '7']
还有另一个list_B:
['2','6','7']
我想检查一下:对于“list_A”中的每个元素,如果它是“list_B”中的元素之一
所以:
for 0 <-> are you one of these? ['2','6','7']
for 1 <-> are you one of these? ['2','6','7']
for 2 <-> are you one of these? ['2','6','7']
最后,我想提出一个“list_C”,它在元素计数方面与“list_A”相同,但更像是一个看起来像这样的地图:
['-1', '-1', '2', '-1', '-1', '-1', '6', '7']
即:每个非匹配元素为“-1”,每个匹配元素为“self”。显然,我正在为每个周期嵌套 2 个,并且它有效:
myStateMap = []
for a in list_A:
elementString = -1
for b in list_B:
if a == b:
# Update the elementString in case of a match
elementString = a
print "\tMatch"
else:
pass
print "\tNO Match!"
# Store the elementString
myStateMap.append(elementString)
问题是:您将如何优化它?您将如何使其更短、更高效?