我想这样做,但是在python中:
从[list]中选择*其中[element at index n]=“你好”
到目前为止,我有这个
cells = [' ','hello',' ',' ',' ',' ',' ',' ',' ']
emptySpots = []
for s in range(len(cells)):
if cells[s] == 'hello':
emptySpots.append(s)
这给了我一个包含“hello”的单元格的索引列表,但是我敢打赌还有一种更直接的(pythonesque)方法来实现这一点。在
最好是一个一行程序,它只返回单元格中等于“”的元素数的计数。在
或者
^{pr2}$我不确定您是否希望从列表中返回匹配元素的列表(标题是“in python,using in,get specific elements”),还是希望计算它们的所有出现次数。您可以使用
filter
或list comprehension从列表中返回匹配元素,然后对结果调用len
来计算它发生的次数。如果你只关心一个项在列表中出现的次数,list.count
是最好的方法。在len(filter(lambda x: 'hello' == x, cells))
len([x for x in cells if x == 'hello'])
{如果你想数一数的话:
cells.count(' ')
下面是一个列表理解与过滤器的简单工作台:
你的问题令人困惑。代码不获取空单元格的索引,而是获取元素
hello
的索引。在你好像有两个问题在一个?在
如果您真的想得到您在上一句话中声明的“空单元格”的数量,可以使用
list.count
:相关问题 更多 >
编程相关推荐