给定一个列表[“foo”、“bar”、“baz”]和列表“bar”中的一个项,如何获取其索引1?
当前回答
python中的某些结构包含一个索引方法,可以很好地解决这个问题。
'oi tchau'.index('oi') # 0
['oi','tchau'].index('oi') # 0
('oi','tchau').index('oi') # 0
参考文献:
在列表中
在元组中
字符串中
其他回答
对此有一个更实用的答案。
list(filter(lambda x: x[1]=="bar",enumerate(["foo", "bar", "baz", "bar", "baz", "bar", "a", "b", "c"])))
更通用的形式:
def get_index_of(lst, element):
return list(map(lambda x: x[0],\
(list(filter(lambda x: x[1]==element, enumerate(lst))))))
python中的一个简单解决方案:
li1=["foo","bar","baz"]
for i in range(len(li1)):
if li1[i]=="bar":
print(i)
列表元素的数据类型无关紧要。只需将“bar”替换为您要查找的元素。我们还可以为此编写一个函数:
def indexfinder(element,lis):
for i in range(len(lis)):
if lis[i]==element:
return i
这里提出的所有函数都再现了固有的语言行为,但掩盖了正在发生的事情。
[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
如果语言提供了自己想要的方法,为什么要编写带有异常处理的函数?
获取列表中一个或多个(相同)项的所有出现次数和位置
使用enumerate(list),您可以存储第一个元素(n),当元素x等于您查找的值时,该元素是列表的索引。
>>> alist = ['foo', 'spam', 'egg', 'foo']
>>> foo_indexes = [n for n,x in enumerate(alist) if x=='foo']
>>> foo_indexes
[0, 3]
>>>
让我们让函数findindex
此函数将项和列表作为参数,并返回项在列表中的位置,就像我们之前看到的那样。
def indexlist(item2find, list_or_string):
"Returns all indexes of an item in a list or a string"
return [n for n,item in enumerate(list_or_string) if item==item2find]
print(indexlist("1", "010101010"))
输出
[1, 3, 5, 7]
易于理解的
for n, i in enumerate([1, 2, 3, 4, 1]):
if i == 1:
print(n)
输出:
0
4
对于一个可比的
# 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()]
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录