简体   繁体   English

如何在python的列表中打印特定索引的元素?

[英]How to print elements of particular index in list in python?

Suppose I have list as lists=[1,2,3,3,4,43] now i want to access 5 index element from the above list how can i do that?假设我有 list lists=[1,2,3,3,4,43]现在我想访问上面列表中的 5 个索引元素,我该怎么做? I Tried sorting the list我尝试对列表进行排序

lists.sort()
z=len(lists)
lists.index(z-1)

on trying to get 5th item ie 4 it says value not in list.在尝试获得第 5 项即 4 时,它表示值不在列表中。 how can I do that?我怎样才能做到这一点?

lists.index(z-1)

index() is an inbuilt function in Python, which searches for given element from start of the list and returns the lowest index where the element appears. index() 是 Python 中的一个内置函数,它从列表的开头搜索给定元素并返回该元素出现的最低索引。

In your case z=6 and z-1=5, as 5 is not present in the list it returns在您的情况下,z=6 和 z-1=5,因为 5 不在它返回的列表中

ValueError: 5 is not in list ValueError: 5 不在列表中

To get value use following要获得以下价值使用

lists[z-1]列表[z-1]

it will return the value at the given index ie.它将返回给定索引处的值,即。 value at z-1 index z-1 索引处的值

To get the 5th index you should do: 'list[4]'要获得第 5 个索引,您应该执行:'list[4]'

What you tried 'list.index(6-1)' will return the index of the first value that equals 5您尝试过的“list.index(6-1)”将返回等于 5 的第一个值的索引

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

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