Python 2列表理解和评估 [英] Python 2 list comprehension and eval

查看:70
本文介绍了Python 2列表理解和评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您如何在列表理解或评估中使用多行语句?

How do you have a multiple line statement in either a list comprehension or eval?

我正在尝试输入以下代码:

I was trying to turn this code:

def f(x, y, b=''):
    for i in x:
        if i in y:
            y.remove(i)
            i *= 2
        b += i
    return b

像这样进入lambda函数:

Into a lambda function like so:

j=lambda x,y:''.join(eval('y.remove(i);i*2')if i in y else i for i in x)

在两个x中都是一个字符串,例如'onomatopoeia',而y是一个列表,例如['o','a','o'].

In both x is a string such as 'onomatopoeia' and y is a list such as ['o','a','o'].

但是由于某种原因,它返回语法错误.谁能解释一下?

But for some reason, it returns a syntax error. Can anyone explain this?

推荐答案

首先,由于循环中的副作用,您可能不应该使用lambda重写它.无论如何,如果不要,请不要使用eval.

First, you probably shouldn't rewrite this with a lambda because of the side-effects in the loop. If you really want to anyway, don't use an eval.

我建议:

j = lambda x, y: ''.join((y.remove(i) or 2 * i) if i in y else i for i in x)

因为remove的结果是None,所以or的第二个参数将是结果.这样可以避免评估.但是比for循环还糟糕.

Because the result of remove is None the second argument to or will be the result. This avoids the eval. But it's still worse then a for-loop.

如对原始问题的评论中所述,2 * y.pop(y.index(i))or构造更具可读性.您将在y上循环两次,但是性能似乎不是问题.

As noted in comments on the original question, 2 * y.pop(y.index(i)) is more readable than the or construct. You'll loop twice over y, but performance doesn't seem the issue.

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

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