Python列表操作 [英] Python list operation
问题描述
我有两个列表 ListA 和 ListB 如下:
ListA=['1','1','2','2','2','3','4','4','5','5','5','5']
ListB=['1','5']
我正在尝试提出长度与 List A 相同的 List C ,但是将 List A 中的数字替换为如果数字在列表B 中,则为'X'.我期望的结果是:
I am trying to come up with List C which has the same length as List A but replace the numbers in the List A with 'X' if the number is in the List B.The result i am expecting:
ListC=['X','X','2','2','2','3','4','4','X','X','X','X']
仅供参考, ListB 的长度将始终小于 ListA 的长度,而 ListB 的长度将不包含任何不在列表A .
FYI, length of ListB will always less than the length of ListA and ListB will not hold any numbers that is not in List A.
我尝试过这样:
ListA=['1','1','2','2','2','3','4','4','5','5','5','5']
ListB=['1','5']
ListC=[]
for items in ListB:
for a in ListA:
if items==a:
ListC.append('X')
else:
ListC.append(a)
很显然,这将创建一个列表(具有listB的长度X长度A),而不只是列表A的长度.是否有任何内置函数可以执行此操作?谁能给我一个提示,怎么做?
obviously this will create a List that has (length of listB X lenght A) rather than just just the length of list A. Is there any built in function that does this operation? Could anyone give me a clue how to do it?
推荐答案
您可以使用列表理解:
[i if i not in ListB else 'X' for i in ListA]
要修复您当前的代码,请使用in
检查项目是否在ListB
中:
To fix your current code, use in
to check to see if the item is in ListB
:
for item in ListA:
if item in ListB:
ListC.append('X')
else:
ListC.append(item)
这篇关于Python列表操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!