简体   繁体   English

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

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

I want to be able to print the middle element of a list .我希望能够打印列表的中间元素。 The list might be just strings, integers or mixed.该列表可能只是字符串、整数或混合。 I tried this, by finding the index of the middle element, but doesn't work.我通过找到中间元素的索引来尝试这个,但不起作用。 (It prints 2) (它打印 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])

In case you want to round down for odd amount of list elements, you can use math.trunc for all cases:如果您想对奇数数量的列表元素进行四舍五入,您可以对所有情况使用math.trunc

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

You cannot use list as a variable name, it is already reserved.你不能使用list作为变量名,它已经被保留了。 Second, comments in python should be like this # comment not //comment .其次,python 中的注释应该是这样的#comment not //comment

The following code works just fine:下面的代码工作得很好:

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