列表理解中的中间变量,用于同时进行过滤和转换 [英] Intermediate variable in a list comprehension for simultaneous filtering and transformation

查看:62
本文介绍了列表理解中的中间变量,用于同时进行过滤和转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要归一化的向量列表(在Python中),同时删除了原本具有较小规范的向量.

I have a list of vectors (in Python) that I want to normalize, while at the same time removing the vectors that originally had small norms.

例如,输入列表是

a = [(1,1),(1,2),(2,2),(3,4)]

我需要输出为(x*n, y*n)n = (x**2+y**2)**-0.5

例如,如果我只需要规范,则列表理解将很容易:

If I just needed the norms, for example, that would be easy with a list comprehension:

an = [ (x**2+y**2)**0.5 for x,y in a ]

例如,也只存储一个标准化的x也很容易,但是我想要的是让这个临时变量"n"在两个计算中使用,然后将其丢弃.

It would be also easy to store just a normalized x, too, for example, but what I want is to have this temporary variable "n", to use in two calculations, and then throw it away.

我也不能只使用lambda函数,因为我还需要n来过滤列表.那么最好的方法是什么?

I can't just use a lambda function too because I also need the n to filter the list. So what is the best way?

现在我在这里使用此嵌套列表推导(内部列表中有一个表达式):

Right now I am using this nested list comprehension here (with an expression in the inner list):

a = [(1,1),(1,2),(2,2),(3,4)]

[(x*n,y*n) for (n,x,y) in (( (x**2.+y**2.)**-0.5 ,x,y) for x,y in a) if n < 0.4]

# Out[14]: 
# [(0.70710678118654757, 0.70710678118654757),
#  (0.60000000000000009, 0.80000000000000004)]

内部列表生成具有额外值(n)的元组,然后将这些值用于计算和过滤.这真的是最好的方法吗?我应该意识到有什么可怕的低效率之处吗?

The inner list generates tuples with an extra value (n), and then I use these values for the calculations and filtering. Is this really the best way? Are there any terrible inefficiencies I should be aware of?

推荐答案

Is this really the best way?

好吧,它确实有效地工作,如果您真的要写单行纸,那是您所能做的最好的事情.

Well, it does work efficiently and if you really, really want to write oneliners then it's the best you can do.

另一方面,简单的4行函数将使工作更加清晰:

On the other hand, a simple 4 line function would do the same much clearer:

def normfilter(vecs, min_norm):
    for x,y in vecs:
        n = (x**2.+y**2.)**-0.5
        if min_norm < n:
            yield (x*n,y*n)

normalized = list(normfilter(vectors, 0.4))

顺便说一句,您的代码或描述中有错误-您说过滤掉了简短的向量,但代码却相反:p

Btw, there is a bug in your code or description - you say you filter out short vectors but your code does the opposite :p

这篇关于列表理解中的中间变量,用于同时进行过滤和转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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