繁体   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