gpt4 book ai didi

Python 查找并替换列表中的最后一次出现

转载 作者:行者123 更新时间:2023-11-28 22:33:58 25 4
gpt4 key购买 nike

在 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 查找并替换列表中的最后一次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39374355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com