Python:列表推导式中的'as'关键字?

7 投票
4 回答
2902 浏览
提问于 2025-04-18 08:31

我知道这样做是行不通的,但你们明白我的意思。

c = [m.split('=')[1] as a for m in matches if a != '1' ]

有没有办法实现这个呢?如果你使用像这样的列表推导

c = [m.split('=')[1] as a for m in matches if m.split('=')[1] != '1' ]

那么会从 split 中生成两个列表,对吧?

4 个回答

1

也许可以这样做:

c = [ a for a, m in map(lambda x: (x.split('=')[1], x), matches) if a != '1' ]

你可能想用 imap 来代替 map。这里有一个更简洁的版本:

def right_eq(x): return (x.split('=')[1], x)

c = [ a for a, m in imap(right_eq, matches) if a != '1' ]
3

你不能这样做,而且使用嵌套的 map 或者嵌套的列表推导式其实没有什么实际意义,其他的解决方案也说明了这一点。如果你想对列表进行预处理,可以直接这样做:

whatIwant = (m.split('=')[1] for m in matches)
c = [a for a in whatIwant if a != 1]

使用嵌套的列表推导式或者 map 并不会节省任何东西,因为整个列表还是会被处理。这样做只是让代码变得不那么容易读懂。

3

这其实是有点可能的,但如果你不得不使用像下面这样的糟糕方法,那就该考虑用一个普通的循环了:

c = [a for m in matches for a in [m.split('=')[1]] if a != '1']
9

你可以在列表推导式里面使用生成器表达式:

c = [a for a in (m.split('=')[1] for m in matches) if a != '1']

撰写回答