在python中,使用in,获取特定元素

2024-10-01 09:34:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我想这样做,但是在python中:

从[list]中选择*其中[element at index n]=“你好”

到目前为止,我有这个

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

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

这给了我一个包含“hello”的单元格的索引列表,但是我敢打赌还有一种更直接的(pythonesque)方法来实现这一点。在

最好是一个一行程序,它只返回单元格中等于“”的元素数的计数。在


Tags: inhello列表forindexlenifrange
3条回答
[i for i in range(len(cells)) if cells[i] == "hello"]

或者

^{pr2}$

我不确定您是否希望从列表中返回匹配元素的列表(标题是“in python,using in,get specific elements”),还是希望计算它们的所有出现次数。您可以使用filterlist comprehension从列表中返回匹配元素,然后对结果调用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

你的问题令人困惑。代码不获取空单元格的索引,而是获取元素hello的索引。在

你好像有两个问题在一个?在

如果您真的想得到您在上一句话中声明的“空单元格”的数量,可以使用list.count

empty_spots = cells.count(' ')

相关问题 更多 >