I want to do something like this, but in python :
select * from [list] where [element at index n] = 'hello'
So far, I have this
cells = [' ','hello',' ',' ',' ',' ',' ',' ',' ']
emptySpots = []
for s in range(len(cells)):
if cells[s] == 'hello':
emptySpots.append(s)
This gives me a list of the indexes of the cells with 'hello' in them, but I bet theres a more straightforeward (pythonesque) way to do this.
What would be nice is a one liner that just returns the count of the number of elements in cells that equal ' '.
Your question is confusing. Your code does not get the indexes of the empty cells but of the element hello.
It seems you have two questions in one?
If you really want to get the number of "empty cells" like you claim in your last sentence, you can use list.count:
empty_spots = cells.count(' ')
I wasn't sure if you wanted to return a list of matching elements from a list (the title being "in python, using in, get specific elements"), or if you wanted to count all occurrences of them. You can use filter or a list comprehension to return matching elements from a list, and then call len on the result to count the number of times it occurs. If all you care about is finding the number of times an item occurs in a list list.count is the best approach.
len(filter(lambda x: 'hello' == x, cells))
len([x for x in cells if x == 'hello'])
And as answered here (definitely the nicest way if you just wanted to count them!):
cells.count(' ')
Here's a simple bench of list comprehension vs filter:
% python -m timeit -s "data = ['hello' for x in range(100000)]" "[x for x in data if x == 'hello']"
100 loops, best of 3: 6.97 msec per loop
% python -m timeit -s "data = ['hello' for x in range(100000)]" "filter(lambda x: x == 'hello', data)"
100 loops, best of 3: 13.3 msec per loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With