[英]Python list limit specific elements to N times
I have a list with 7 items inside like ['S1','S1','S1','S1','L','L','L']
and I want to limit 'L'
to be only 2 times and the rest to be 'S1'
.我有一个包含 7 个项目的列表,例如
['S1','S1','S1','S1','L','L','L']
我想将'L'
限制为只有 2时间和 rest 是'S1'
。
Try it:尝试一下:
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)
Using a counter to count the occurrences of L
elem in the list and append accordingly:使用计数器计算列表中
L
elem 的出现次数,并相应地计算 append:
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)
OUTPUT: OUTPUT:
['S1', 'S1', 'S1', 'S1', 'L', 'L']
Edit :编辑:
if you want to replace the rest of the L
to the S1
:如果要将
L
的 rest 替换为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)
OUTPUT: OUTPUT:
['S1', 'S1', 'S1', 'S1', 'L', 'L', 'S1']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.