简体   繁体   English

Python:访问列表中的多个元素

[英]Python: access multiple elements in list

I have the following list: 我有以下清单:

my_list = ["shanya", 1.2, 1, False, "test", 2, 3.3, True, "3", "4.0"]

But how do I access multiple elements in this list? 但是,如何访问此列表中的多个元素?

I know how to access one specific element (eg, my_list[1] gives me [1.2] ) and a range (eg, my_list[1:3] gives me [1.2, 1] ) but how do I get the first and third to last element? 我知道如何访问一个特定元素(例如, my_list[1]给我[1.2] )和一个范围(例如, my_list[1:3]给我[1.2, 1] ),但是如何获得第一个和第三个最后一个元素?

["shanya", 1, False, "test", 2, 3.3, True, "3", "4.0"]

You can use itemgetter : 您可以使用itemgetter

>>> from operator import itemgetter

>>> values = ["shanya", 1.2, 1, False, "test", 2, 3.3, True, "3", "4.0"]

>>> itemgetter(0, -3)(values)
('shanya', True)

Simply contact the sub-lists, like: 只需联系子列表,例如:

result = l[:1] + l[2:]

output: 输出:

['shanya', 1, False, 'test', 2, 3.3, True, '3', '4.0']

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

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