Reputation: 37
I am very new to Python, but I have a problem that Google hasn't yet solved for me. I have a list of strings (f_list). I would like to generate a list of the indicies of the strings that contain a specific character ('>').
Example: f_list = ['>EntryA', EntryB, '>EntryC', EntryD]
I would like to generate: index_list = [0, 2]
This code works, but I have to enter the exact name of a string (ie. >EntryA) for Value. If I enter '>' (as indicated below in the code example), it returns no values in index_list.
f_list = ['>EntryA', 'EntryB', '>EntryC', 'EntryD']
index_list = []
def all_indices(v, qlist):
idx = -1
while True:
try:
idx = qlist.find(v, idx+1)
index_list.append(idx)
except ValueError:
break
return index_list
all_indices('>', f_list)
print(index_list)
Upvotes: 1
Views: 3382
Reputation: 60024
If you are ever working with indexes, enumerate()
is your function:
>>> f_list = ['>EntryA', 'EntryB', '>EntryC', 'EntryD']
>>> for i, j in enumerate(f_list):
... if '>' in j:
... print i
...
0
2
In a function:
>>> def all_indices(v, qlist):
... return [i for i, j in enumerate(f_list) if '>' in j]
...
>>> all_indices('>', f_list)
[0, 2]
Upvotes: 0
Reputation: 104092
You can use filter to find the strings:
>>> f_list = ['>EntryA', 'EntryB', '>EntryC', 'EntryD']
>>> filter(lambda s: '>' in s, f_list)
['>EntryA', '>EntryC']
Or use a list comprehension to find the indices:
>>> [i for i, s in enumerate(f_list) if '>' in s]
[0, 2]
Or you can find both with either:
>>> filter(lambda s: '>' in s[1], enumerate(f_list))
[(0, '>EntryA'), (2, '>EntryC')]
>>> [(i, s) for i, s in enumerate(f_list) if '>' in s]
[(0, '>EntryA'), (2, '>EntryC')]
Upvotes: 2