是否存在从列表中仅获取某些值的"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)
lst = line.split(',')
one, four, ten = lst[1], lst[4], lst[10]
Run Code Online (Sandbox Code Playgroud)
试试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)