Python列表理解功能可创建多个列表 [英] Python list comprehensions to create multiple lists

查看:103
本文介绍了Python列表理解功能可创建多个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建两个列表listOfAlistOfB来存储另一个列表s中AB的索引.

I want to create two lists listOfA and listOfB to store indices of A and B from another list s.

s=['A','B','A','A','A','B','B']

输出应为两个列表

listOfA=[0,2,3,4]
listOfB=[1,5,6]

我可以用两个语句来做到这一点.

I am able to do this with two statements.

listOfA=[idx for idx,x in enumerate(s) if x=='A']
listOfB=[idx for idx,x in enumerate(s) if x=='B']

但是,我只想使用列表推导进行一次迭代. 是否可以在单个语句中完成? 类似于listOfA,listOfB=[--code goes here--]

However, I want to do it in only one iteration using list comprehensions only. Is it possible to do it in a single statement? something like listOfA,listOfB=[--code goes here--]

推荐答案

列表理解的确切定义是产生一个列表对象.您的2个列表对象甚至具有不同的长度;您将不得不使用副作用来实现您想要的.

The very definition of a list comprehension is to produce one list object. Your 2 list objects are of different lengths even; you'd have to use side-effects to achieve what you want.

请勿在此处使用列表推导.只需使用普通循环即可:

Don't use list comprehensions here. Just use an ordinary loop:

listOfA, listOfB = [], []

for idx, x in enumerate(s):
    target = listOfA if x == 'A' else listOfB
    target.append(idx)

这使您只需执行一个循环;这将击败任何两个列表理解,至少直到开发人员找到一种使列表理解构建列表的方法快于使用单独的list.append()调用循环的两倍时为止.

This leaves you with just one loop to execute; this will beat any two list comprehensions, at least not until the developers find a way to make list comprehensions build a list twice as fast as a loop with separate list.append() calls.

我每天都会通过嵌套列表理解 just 来进行选择,以便能够在一行上生成两个列表.正如 Python的禅宗所述:

I'd pick this any day over a nested list comprehension just to be able to produce two lists on one line. As the Zen of Python states:

可读性计数.

Readability counts.

这篇关于Python列表理解功能可创建多个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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