给定一个列表[“foo”、“bar”、“baz”]和列表“bar”中的一个项,如何获取其索引1?
当前回答
name ="bar"
list = [["foo", 1], ["bar", 2], ["baz", 3]]
new_list=[]
for item in list:
new_list.append(item[0])
print(new_list)
try:
location= new_list.index(name)
except:
location=-1
print (location)
这说明了如果字符串不在列表中,如果它不在列表,则位置=-1
其他回答
查找列表L中项目x的索引:
idx = L.index(x) if (x in L) else -1
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
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"])
text = ["foo", "bar", "baz"]
target = "bar"
[index for index, value in enumerate(text) if value == target]
对于一个小的元素列表,这会很好。但是,如果列表包含大量元素,最好应用二进制运行时复杂度为O(logn)的搜索.
对此有一个更实用的答案。
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))))))
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录