2016-08-09 42 views
-1

我在這裏遇到了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,然後應採取中間兩個數字(a & b以上,索引1 & 2),將它們添加和平均:(4 + 8)/2等於6.我的代碼將分配2到a,在列表中查找並返回一個錯誤:2不在new_lst。不是我想要的。

+0

我也想提一下,'new_lst = x'這一行沒有複製列表,它只是創建第二個引用。如果您需要製作副本,請參閱http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list-in-python。我的首選是'copy'軟件包,因爲它很好用,很明確。 – Jud

回答

0

你不想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 
+0

非常感謝@ senshin!這正是我一直在尋找但找不到的! – Cory

2

您在列表中可以用方括號引用一個項目,像這樣

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

I want to return an item found at a particular index.

你想使用[]操作?

new_lst[a]獲得索引a處的new_lst中的項目。

有關該主題的更多信息,請參見this documentation page

相關問題