python列表操作程序,Python列表操作

I have two lists ListA and ListB as follow:

ListA=['1','1','2','2','2','3','4','4','5','5','5','5']

ListB=['1','5']

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']

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.

I have tried like this:

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)

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?

解决方案

You can use a list comprehension:

[i if i not in ListB else 'X' for i in ListA]

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值