In python, using in, get specific elements

I want to do something similar, but in python:

select * from [list], where [element in index n] = 'hello'

I still have this

    cells = [' ','hello',' ',' ',' ',' ',' ',' ',' ']
    emptySpots = []

    for s in range(len(cells)):
        if cells[s] == 'hello':
            emptySpots.append(s)

This gives me a list of cell indexes with โ€œhiโ€ in them, but I'm sure this is a simpler (Pitonessian) way to do this.

What would be nice is a single liner that simply returns the number of elements in cells that are equal. '

+3
source share
4 answers

Your question is confusing. Your code does not get empty cell indices, but an element hello.

It seems you have two questions in one?

" ", , list.count:

empty_spots = cells.count(' ')
+5

, ( " python, in, get specific elements" ) . filter , , len , . , , - , , list.count, - .

len(filter(lambda x: 'hello' == x, cells))

len([x for x in cells if x == 'hello'])

(, , !): cells.count(' ')

:

% 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
+4
[i for i in range(len(cells)) if cells[i] == "hello"]

[i for i, s in enumerate(cells) if s == "hello"]
+3

?

cells = [' ','hello',' ',' ',' ',' ',' ',' ',' ']
matches = map(lambda x: x if cells[x] == 'hello' else False, range(len(cells)))
emptySpots = filter(lambda x: x == False, matches)
+1
source

All Articles