Ken Nguyen Ken Nguyen - 2 months ago 8
Python Question

Python find and replace last appearance in list

In Python, I have a list of list

list3 = ['PA0', 'PA1']
list2 = ['PB0', 'PB1']
list1 = ['PC0', 'PC1', 'PC2']

[(list1[i], list2[j], list3[k]) for i in xrange(len(list1)) for j in xrange(len(list2)) for k in xrange(len(list3))]

#Result
[('PC0', 'PB0', 'PA0'),
('PC0', 'PB0', 'PA1'),
('PC0', 'PB1', 'PA0'),
('PC0', 'PB1', 'PA1'),
('PC1', 'PB0', 'PA0'),
('PC1', 'PB0', 'PA1'),
('PC1', 'PB1', 'PA0'),
('PC1', 'PB1', 'PA1'),
('PC2', 'PB0', 'PA0'),
('PC2', 'PB0', 'PA1'),
('PC2', 'PB1', 'PA0'),
('PC2', 'PB1', 'PA1')]


How can I find the last appearance and add E as suffix


[('PC0', 'PB0', 'PA0'),
('PC0', 'PB0', 'PA1'),
('PC0', 'PB1', 'PA0'),
('PC0E', 'PB1', 'PA1'),
('PC1', 'PB0', 'PA0'),
('PC1', 'PB0', 'PA1'),
('PC1', 'PB1', 'PA0'),
('PC1E', 'PB1', 'PA1'),
('PC2', 'PB0', 'PA0'),
('PC2', 'PB0E', 'PA1'),
('PC2', 'PB1', 'PA0E'),
('PC2E', 'PB1E', 'PA1E')]

Answer

Process your input list in reverse, then mark the first occurrence of any value. You can use a list of sets to track what values you've already seen. Reverse the output list you build when you are done:

seensets = [set() for _ in inputlist[0]]
outputlist = []
for entry in reversed(inputlist):
    newentry = []
    for value, seen in zip(entry, seensets):
        newentry.append(value + 'E' if value not in seen else value)
        seen.add(value)
    outputlist.append(tuple(newentry))
outputlist.reverse()

Demo:

>>> seensets = [set() for _ in inputlist[0]]
>>> outputlist = []
>>> for entry in reversed(inputlist):
...     newentry = []
...     for value, seen in zip(entry, seensets):
...         newentry.append(value + 'E' if value not in seen else value)
...         seen.add(value)
...     outputlist.append(tuple(newentry))
...
>>> outputlist.reverse()
>>> pprint(outputlist)
[('PC0', 'PB0', 'PA0'),
 ('PC0', 'PB0', 'PA1'),
 ('PC0', 'PB1', 'PA0'),
 ('PC0E', 'PB1', 'PA1'),
 ('PC1', 'PB0', 'PA0'),
 ('PC1', 'PB0', 'PA1'),
 ('PC1', 'PB1', 'PA0'),
 ('PC1E', 'PB1', 'PA1'),
 ('PC2', 'PB0', 'PA0'),
 ('PC2', 'PB0E', 'PA1'),
 ('PC2', 'PB1', 'PA0E'),
 ('PC2E', 'PB1E', 'PA1E')]
Comments