繁体   English   中英

使用已知索引在列表中查找项目

[英]Find an item in a list using the known index

我在这里遇到Python问题,需要您的帮助。

我想返回在特定索引处找到的项目。 我不知道该项目是什么,只有索引。 我所发现的一切与我所需要的相反,即,使用myList.index(item)查找已知项的索引。

片段:

new_lst = x
new_lst.sort()
leng = len(new_lst).....

    elif leng > 1 and leng % 2 == 0:
    a = (leng / 2) #or float 2.0
    b = a - 1 
    c = new_lst.index(a) #The problem area
    d = new_lst.index(b) #The problem area
    med = (c + d) / 2.0
    return med ......

仅当anew_lst ,上述内容才会返回。 否则它会出错。 我想得到中间两个数字(如果列表是偶数),将它们加在一起,然后取平均值。

示例: new_lst = [4,3,8,8] 获取em,对em进行排序,然后应该取中间两个数字(上面的ab ,索引1和2),将它们相加并取平均值: (4 + 8) / 2等于6。我的代码将2分配给a ,寻找它在列表中并返回错误:2 not in new_lst 不是我想要的

您可以使用方括号引用列表中的项目,如下所示

c = new_lst[a]
d = new_lst[b]

您不需要list.index函数-这是用于查找项目在列表中的位置。 要在某个位置查找项目,您应该使用切片(在其他语言中,有时也称为“索引编制”,这可能会使您感到困惑)。 将一个元素切出一个可迭代对象看起来像这样: lst[index]

>>> new_lst = [4, 3, 8, 8]
>>> new_lst.sort()
>>> new_lst
[3, 4, 8, 8]

>>> if len(new_lst) % 2 == 0:
    a = new_lst[len(new_lst)//2-1]
    b = new_lst[len(new_lst)//2]
    print((a+b)/2)

6.0

我想返回在特定索引处找到的项目。

您是否要使用[]运算符?

new_lst[a]在索引a处获取new_lst中的项目。

有关主题的更多信息,请参见此文档页面

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM