簡體   English   中英

如何在 Python 中找到列表的中間元素/索引?

[英]How to find the middle element/index of a list in Python?

我希望能夠打印列表的中間元素。 該列表可能只是字符串、整數或混合。 我通過找到中間元素的索引來嘗試這個,但不起作用。 (它打印 2)

list = [1,3,7,"this",3,"that",7]

if int(len(list))<2:
  middle = 1  // if it has less than 2 entries, the first entry is the middle one. 

elif int(len(list)) %2 == 0 :
  middle = int(len(list)/2)

else: 
  middle = int((len(list)/2) - 1)

print(list[middle])

如果您想對奇數數量的列表元素進行四舍五入,您可以對所有情況使用math.trunc

l = [1,3,7,"this",3,"that",7]
middle = math.trunc(len(l)/2)
print(middle)
>>> 3

你不能使用list作為變量名,它已經被保留了。 其次,python 中的注釋應該是這樣的#comment not //comment

下面的代碼工作得很好:

listt = [1,3,7,"this",3,"that", 7]
middle = int((len(listt)/2)) 
print(listt[middle])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM