python从列表中选择特定元素 [英] python select specific elements from a list

查看:1713
本文介绍了python从列表中选择特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种"pythonic"方式,仅从列表中获取某些值,类似于以下perl代码:

Is there a "pythonic" way of getting only certain values from a list, similar to this perl code:

my ($one,$four,$ten) = line.split(/,/)[1,4,10]

推荐答案

我认为您正在寻找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')

这篇关于python从列表中选择特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆