在Python中,我有一个列表
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')]
如何找到最后一个外观并添加E作为后缀
[(“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')]
最佳答案
反向处理输入列表,然后标记任何值的第一次出现。您可以使用集合列表来跟踪已经看到的值。完成后反转生成的输出列表:
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()
演示:
>>> 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')]
关于python - Python查找并替换列表中的最后一个外观,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39374355/