I have a list like the following:
['ABC ', '02:20', 123456, 123, '-', 123456, 123, 'DEF ', '-', 123456, 123, '-', 123456, 123, 'IFG', '-', 123456, 123, '-', 123456, 123, 'IJK', '03:40', 123456, 123, '-', 123456, 123, 'LOM', '-', 123456, 123, '03:00', 123456, 123]
How do I delete next two elements along with current element based on a condition ?
Such as I want to delete -
and the next 2 elements as well
for idx, val in enumerate(n1):
if val == '-':
del n1[idx]
del n1[idx+1]
del n1[idx+2]
n1 = n1
But only -
is removed from the list
First problem is that after executing del n1[idx]
, the next value, previously at idx+1
is now at position idx
as it have moved forward, so to delete 3 consecutives elements the code would
del n1[idx] del n1[idx] del n1[idx] # OR del n1[idx:idx+3]
But as you iterating while removing, you'll miss elements, and you code would return the following, there 5 removals done but 2 misses
['ABC ', '02:20', 123456, 123, 'DEF ', '-', 123456, 123, 'IFG', '-', 123456, 123, 'IJK', '03:40', 123456, 123, 'LOM', '03:00', 123456, 123]
A solution is to not iterate, but rather check&remove until there is no '-'
left
while '-' in n1:
idx = n1.index('-')
del n1[idx:idx + 3]
您可以通过以下方式从列表中删除元素,
del n1[idx:idx+2]
Each time you execute del n1[idx]
, an element will be removed from the list, and therefore the indices of all elements after the deleted one will change.
Therefore, the following del n1[idx+1]
will be deleting the wrong element.
To avoid this, you can delete the elements in decreasing order of index:
del n1[idx+2]
del n1[idx+1]
del n1[idx]
(And of course you should check if idx+2
and idx+1
are still within the bounds of the list).
just loop and create a new list based on your logic. see below
lst = ['ABC ', '02:20', 123456, 123, '-', 123456, 123, 'DEF ', '-', 123456, 123, '-', 123456, 123, 'IFG', '-', 123456,
123, '-', 123456, 123, 'IJK', '03:40', 123456, 123, '-', 123456, 123, 'LOM', '-', 123456, 123, '03:00', 123456,
123]
idx = 0
lst1 = []
while idx < len(lst) - 1:
if lst[idx] == '-':
idx += 3
else:
lst1.append(lst[idx])
idx += 1
print(lst1)
output
['ABC ', '02:20', 123456, 123, 'DEF ', 'IFG', 'IJK', '03:40', 123456, 123, 'LOM', '03:00', 123456]
Not elegant but works and easily understandable, can easily be used with numba if the dataset is huge.
n1 = ['ABC ', '02:20', 123456, 123, '-', 123456, 123, 'DEF ', '-', 123456, 123, '-', 123456, 123, 'IFG', '-', 123456, 123, '-', 123456, 123, 'IJK', '03:40', 123456, 123, '-', 123456, 123, 'LOM', '-', 123456, 123, '03:00', 123456, 123]
skip = 0
result = []
for idx, val in enumerate(n1):
if val == '-':
skip = 3
else:
skip -= 1
if skip <= 0:
result.append(val)
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.