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'
.
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:
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:
['S1', 'S1', 'S1', 'S1', 'L', 'L']
Edit :
if you want to replace the rest of the L
to the 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:
['S1', 'S1', 'S1', 'S1', 'L', 'L', 'S1']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.