给定一个列表[“foo”、“bar”、“baz”]和列表“bar”中的一个项,如何获取其索引1?
当前回答
me = ["foo", "bar", "baz"]
me.index("bar")
您可以将此应用于列表中的任何成员以获取其索引
其他回答
index()返回值的第一个索引!
|索引(…)|L.index(value,[start,[stop]])->integer--返回值的第一个索引
def all_indices(value, qlist):
indices = []
idx = -1
while True:
try:
idx = qlist.index(value, idx+1)
indices.append(idx)
except ValueError:
break
return indices
all_indices("foo", ["foo","bar","baz","foo"])
下面是使用Python的index()函数的两行代码:
LIST = ['foo' ,'boo', 'shoo']
print(LIST.index('boo'))
输出:1
Python方式将使用enumerate,但您也可以使用来自运算符模块的indexOf。请注意,如果b不在a中,这将引发ValueError。
>>> from operator import indexOf
>>>
>>>
>>> help(indexOf)
Help on built-in function indexOf in module _operator:
indexOf(a, b, /)
Return the first index of b in a.
>>>
>>>
>>> indexOf(("foo", "bar", "baz"), "bar") # with tuple
1
>>> indexOf(["foo", "bar", "baz"], "bar") # with list
1
正如@TerryA所指出的,许多答案讨论了如何找到一个索引。
moreintertools是一个第三方库,它提供了在可迭代文件中查找多个索引的工具。
鉴于
import more_itertools as mit
iterable = ["foo", "bar", "baz", "ham", "foo", "bar", "baz"]
Code
查找多个观测值的索引:
list(mit.locate(iterable, lambda x: x == "bar"))
# [1, 5]
测试多个项目:
list(mit.locate(iterable, lambda x: x in {"bar", "ham"}))
# [1, 3, 5]
另请参阅more_itertools.locate的更多选项。通过>pip Install more_itertools安装。
对于一个可比的
# Throws ValueError if nothing is found
some_list = ['foo', 'bar', 'baz'].index('baz')
# some_list == 2
自定义谓词
some_list = [item1, item2, item3]
# Throws StopIteration if nothing is found
# *unless* you provide a second parameter to `next`
index_of_value_you_like = next(
i for i, item in enumerate(some_list)
if item.matches_your_criteria())
按谓词查找所有项的索引
index_of_staff_members = [
i for i, user in enumerate(users)
if user.is_staff()]
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象