我有一个类似的字符串列表:
['1 2 3 4 5', '1 2 3 4 5',...]
我只想要例如每个字符串的第三和第五个元素:
[(3,5), (3,5),...]
我该怎么做:
[(ans[2],ans[4]); ans.split() for ans in answers]
?
答案 0 :(得分:9)
使用operator.itemgetter
从不同的索引中获取多个项目:
from operator import itemgetter
lst = ['1 2 3 4 5', '1 2 3 4 5']
f = itemgetter(2, 4) # get third and fifth items
r = [f(x.split()) for x in lst]
print(r)
# [('3', '5'), ('3', '5')]
很酷的是,它也适用于切片对象:
f = itemgetter(2, 4, slice(3, 0, -1))
r = [f(x.split()) for x in lst]
print(r)
# [('3', '5', ['4', '3', '2']), ('3', '5', ['4', '3', '2'])]
答案 1 :(得分:6)
您首先执行映射,例如使用发布者:
(ans.split() for ans in answers)
然后你迭代生成器,进一步处理中间结果,如:
[(imm[2],imm[4]) for imm in (ans.split() for ans in answers)]
产生
>>> [(imm[2],imm[4]) for imm in (ans.split() for ans in answers)]
[('3', '5'), ('3', '5')]