Python列表将特定元素限制为N次



我有一个列表,里面有7个项目,比如['S1','S1','S1','S1','L','L','L'],我想将'L'限制为2次,其余的限制为'S1'

使用计数器统计列表中Lelem的出现次数,并相应地追加:

s = ['S1','S1','S1','S1','L','L','L']
c = 0
res = []
for el in s:
if el != 'L':
res.append(el)
elif c < 2:
c += 1
res.append(el)   
print(res)

输出:

['S1', 'S1', 'S1', 'S1', 'L', 'L']

编辑

如果要将L的其余部分替换为S1:

s = ['S1','S1','S1','S1','L','L','L']
c = 0
res = []
for el in s:
if el != 'L':
res.append(el)
else:
if c < 2:
c += 1
res.append(el)
else:
res.append("S1")
print(res)

输出:

['S1', 'S1', 'S1', 'S1', 'L', 'L', 'S1']

试试看:

lst = ["S1","S1","S1","S1","L","L","L"]
limit = 2
value = "L"
new_lst = []
counter = 0
for i in lst:
if counter == limit and i == value:
continue
if i == value:
counter += 1
new_lst.append(i)
print(new_lst)

最新更新