Skip to main content
 首页 » 编程设计

python之如何改进 Python 中的以下列表到列表查找

2025年05月04日14qq78292959

我有以下列表_A:

['0', '1', '2', '3', '4', '5', '6', '7'] 

和其他列表_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”相同,但更像是一个看起来像这样的 map :

['-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) 

问题是:您将如何优化它?您将如何使其更短、更高效?

请您参考如下方法:

您可以使用 list comprehension :

>>> [('-1' if item not in list_B else item) for item in list_A] 
['-1', '-1', '2', '-1', '-1', '-1', '6', '7']