Chris Aung
Chris Aung

Reputation: 9492

python list compare and replace

i have 2 lists. First list, listA is a list of lists.

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

Second list, listB is a list that i am gonna compare against other lists in listA

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

i want to compare the lists in listA individually and replace with 'T' if the list item exist in listB. If not, keep the listB item. It should be something like this

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

I have tried something like this:

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

Doesn't seem to work. Can anyone help me with this?

Upvotes: 1

Views: 1825

Answers (3)

jamylak
jamylak

Reputation: 133514

The solution by @DaoWen is nice, to be more efficient you may pre-convert the list elements to sets:

>>> listA=[[1,2,5,3],[3,1,5],[7,9,2]]
>>> listB=[1,2,3,4,5,6,7,8,9,10]
>>> setA = [set(A) for A in listA]
>>> [['T' if x in A else x for x in listB] for A in setA]
[['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]]

Upvotes: 0

DaoWen
DaoWen

Reputation: 33019

You should use list comprehensions:

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

The parentheses are not necessary, but they might make it a bit more readable.

x if cond else y is Python's equivalent of the ternary operator.

[ f(x) for x in xs ] produces a new list where the function f has been applied to every element in the collection xs.

Upvotes: 8

TerryA
TerryA

Reputation: 59974

Nice and readable :)

listC = []
for i in listA:
    temp = []
    for x in listB:
        if x in i:
            temp.append('T')
        else:
            temp.append(x)
    listC.append(temp)

print listC

Prints:

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

Upvotes: 2

Related Questions