给定一个列表[“foo”、“bar”、“baz”]和列表“bar”中的一个项,如何获取其索引1?
当前回答
可以使用zip()函数获取列表中值的索引。代码可以是:;
list1 = ["foo","bar","baz"]
for index,value in zip(range(0,len(list1)),list1):
if value == "bar":
print(index)
其他回答
这里提出的所有函数都再现了固有的语言行为,但掩盖了正在发生的事情。
[i for i in range(len(mylist)) if mylist[i]==myterm] # get the indices
[each for each in mylist if each==myterm] # get the items
mylist.index(myterm) if myterm in mylist else None # get the first index and fail quietly
如果语言提供了自己想要的方法,为什么要编写带有异常处理的函数?
如果元素不在列表中,则会出现问题。此函数处理以下问题:
# if element is found it returns index of element else returns None
def find_element_in_list(element, list_element):
try:
index_element = list_element.index(element)
return index_element
except ValueError:
return None
下面是使用Python的index()函数的两行代码:
LIST = ['foo' ,'boo', 'shoo']
print(LIST.index('boo'))
输出:1
请尝试以下代码:
["foo", "bar", "baz"].index("bar")
参考:https://www.programiz.com/python-programming/methods/list/index
FMc和user7177的答案的变体将给出一个可以返回任何条目的所有索引的dict:
>>> a = ['foo','bar','baz','bar','any', 'foo', 'much']
>>> l = dict(zip(set(a), map(lambda y: [i for i,z in enumerate(a) if z is y ], set(a))))
>>> l['foo']
[0, 5]
>>> l ['much']
[6]
>>> l
{'baz': [2], 'foo': [0, 5], 'bar': [1, 3], 'any': [4], 'much': [6]}
>>>
您还可以将其用作一行程序来获取单个条目的所有索引。虽然我确实使用了set(a)来减少lambda的调用次数,但并不能保证效率。
推荐文章
- 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中重置生成器对象