Reputation: 23
I'm stuck on something, I have a string list that is filled similar to this:
['one', 'two', 'asdf', 'asdf', 'stuff', 'other', 'asdf', 'other stuff', 'asdf','asdf']
This list changes constantly, but the one constant is that 'asdf' will always be there, the data before the first asdf
and after it is what changes.
My issue is I either need to Remove all the strings in the list BEFORE the first asdf (in the example it would be one and two) or count everything After the first asdf.
I'm using:
data2 = normalize_line_endings(data)
data3 = data2.split('\n')
data3 = list(map(lambda x: str(x) if x else 'asdf' , data3))
print(data3)
target_ibdex = data3.rindex('asdf')
target_ibdex2 = target_ibdex
print(data3[:target_ibdex - target_ibdex2])
However when it runs, its using the very last asdf
, so it just deletes the entire string.
I need:
a=['one', 'two', 'asdf', 'asdf', 'stuff', 'other', 'asdf', 'other stuff', 'asdf','asdf']
b = code to delete everything before FIRST asdf
len(b)
where b's value is now 8 instead of 10. since one,two got removed.
Upvotes: 2
Views: 40
Reputation: 49784
You can use list.index() like:
b = a[a.index('asdf'):]
a = ['one', 'two', 'asdf', 'asdf', 'stuff', 'other', 'asdf', 'other stuff',
'asdf', 'asdf']
b = a[a.index('asdf'):]
print(b)
['asdf', 'asdf', 'stuff', 'other', 'asdf', 'other stuff', 'asdf', 'asdf']
Upvotes: 1
Reputation: 95948
This is a perfect use-case for itertools.dropwhile
, if you actually need the elements after:
In [1]: a = ['one', 'two', 'asdf', 'asdf', 'stuff', 'other', 'asdf', 'other stuff', 'asdf','asdf']
In [2]: import itertools
In [3]: list(itertools.dropwhile(lambda x: x != 'asdf', a))
Out[3]: ['asdf', 'asdf', 'stuff', 'other', 'asdf', 'other stuff', 'asdf', 'asdf']
Of course, if you just need the count of elements after, you can simply do:
In [4]: len(a) - a.index('asdf')
Out[4]: 8
Upvotes: 1