如何在列表理解中进行中间过程

时间:2022-10-30 10:19:18

I have a list of string that look like that :

我有一个字符串列表,看起来像这样:

['1 2 3 4 5', '1 2 3 4 5',...]

And I want for example only the third and fifth element of each string :

我只想要例如每个字符串的第三和第五个元素:

[(3,5), (3,5),...]

how can I do something like this :

我该怎么做这样的事情:

[(ans[2],ans[4]); ans.split() for ans in answers]

?

2 个解决方案

#1


9  

Use operator.itemgetter to get multiple items from different indices:

使用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')]

Cool thing is, it also works with slice objects:

很酷的是,它也适用于切片对象:

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'])]

#2


6  

You first perform a mapping, for instance using a genrator:

您首先执行映射,例如使用生成器:

(ans.split() for ans in answers)

and then you iterate over the generator, and process the intermediate result further, like:

然后迭代生成器,进一步处理中间结果,如:

[(imm[2],imm[4]) for imm in (ans.split() for ans in answers)]

generating:

发生:

>>> [(imm[2],imm[4]) for imm in (ans.split() for ans in answers)]
[('3', '5'), ('3', '5')]

#1


9  

Use operator.itemgetter to get multiple items from different indices:

使用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')]

Cool thing is, it also works with slice objects:

很酷的是,它也适用于切片对象:

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'])]

#2


6  

You first perform a mapping, for instance using a genrator:

您首先执行映射,例如使用生成器:

(ans.split() for ans in answers)

and then you iterate over the generator, and process the intermediate result further, like:

然后迭代生成器,进一步处理中间结果,如:

[(imm[2],imm[4]) for imm in (ans.split() for ans in answers)]

generating:

发生:

>>> [(imm[2],imm[4]) for imm in (ans.split() for ans in answers)]
[('3', '5'), ('3', '5')]