python从列表中选择特定元素

enn*_*ler 27 python list

是否存在从列表中仅获取某些值的"pythonic"方式,类似于此perl代码:

my ($one,$four,$ten) = line.split(/,/)[1,4,10]
Run Code Online (Sandbox Code Playgroud)

has*_*2k1 25

使用列表理解

line = '0,1,2,3,4,5,6,7,8,9,10'
lst = line.split(',')
one, four, ten = [lst[i] for i in [1,4,10]]
Run Code Online (Sandbox Code Playgroud)


unu*_*tbu 21

我想你正在寻找operator.itemgetter:

import operator
line=','.join(map(str,range(11)))
print(line)
# 0,1,2,3,4,5,6,7,8,9,10
alist=line.split(',')
print(alist)
# ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
one,four,ten=operator.itemgetter(1,4,10)(alist)
print(one,four,ten)
# ('1', '4', '10')
Run Code Online (Sandbox Code Playgroud)

  • 并不是的.如果你拿出示范代码,它看起来像这样:一,四,十= operator.itemgetter(1,4,10)(line.split(',')) (7认同)

Sil*_*ost 8

lst = line.split(',')
one, four, ten = lst[1], lst[4], lst[10]
Run Code Online (Sandbox Code Playgroud)

  • 更少的代码行==更好的代码是不正确的想法 (4认同)
  • 我想你误解了这个问题 (2认同)

mik*_*iku 5

试试operator.itemgetter(在Python 2.4或更高版本中可用):

返回一个可调用对象,该对象使用操作数的____ getitem ____()方法从其操作数获取项目。如果指定了多个项目,则返回查找值的元组。

>>> from operator import itemgetter
>>> line = ','.join(map(str, range(11)))
>>> line
'0,1,2,3,4,5,6,7,8,9,10'
>>> a, b, c = itemgetter(1, 4, 10)(line.split(','))
>>> a, b, c
('1', '4', '10')
Run Code Online (Sandbox Code Playgroud)

浓缩:

>>> # my ($one,$four,$ten) = line.split(/,/)[1,4,10]
>>> from operator import itemgetter
>>> (one, four, ten) = itemgetter(1, 4, 10)(line.split(','))
Run Code Online (Sandbox Code Playgroud)