Skip to main content
 首页 » 编程设计

python 列表比较和替换

2025年05月04日9oomusou

我有 2 个列表。第一个列表,listA 是列表的列表。

listA=[[1,2,5,3],[3,1,5],[7,9,2]] 

第二个列表,listB 是我要与 listA 中的其他列表进行比较的列表

listB=[1,2,3,4,5,6,7,8,9,10] 

我想单独比较 listA 中的列表,如果列表项存在于 listB 中,则替换为“T”。如果没有,保留 listB 项。应该是这样的

listC=[['T','T','T',4,'T',6,7,8,9,10],['T',2,'T',4,'T',6,7,8,9,10],[1,'T',3,4,5,6,'T',8,'T',10]] 

我试过这样的:

for item in listA: 
    for i in range(10): 
        listC.append([i if i not in item else 'T' for i in listB]) 

好像不行。谁能帮我解决这个问题?

请您参考如下方法:

你应该使用 list comprehensions :

listC = [ [ ('T' if b in a else b) for b in listB ] for a in listA ] 

括号不是必需的,但它们可能会使它更具可读性。

x if cond else y Python 等价于 ternary operator .

[ f(x) for x in xs ]生成一个新列表,其中函数 f已应用于集合中的每个元素 xs .