且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python列表理解功能可创建多个列表

更新时间:2023-02-18 12:25:28

列表理解的确切定义是产生一个列表对象.您的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.