简体   繁体   English

比较 Python 列表中的两个元素

[英]Compare two elements in a Python list

I have a list of three complex numbers, two of them are conjugate of each other and I want to sort them out.我有一个包含三个复数的列表,其中两个是共轭的,我想将它们排序。 Therefore I want to compare a pair of elements of the list and ask if their absolute values (or modulus) of the elements in the list are equal or not.因此,我想比较列表中的一对元素,并询问它们在列表中元素的绝对值(或模数)是否相等。 If the comparison is true, sorting is done.如果比较为真,则排序完成。 See the code below.请参阅下面的代码。 For testing, I did a single element comparison first (if the absolute value exceeds 4 or not).为了测试,我先做了单元素比较(绝对值是否超过4)。 In the last comparison, I tried to use two variables x and y , but the syntax fails.在上次比较中,我尝试使用两个变量xy ,但语法失败。

Can this be corrected or could there be some other tricks?这可以纠正还是可以有其他一些技巧?

z = [complex(2.,-4.79583152), complex(2.,4.79583152), complex(0,1) ]
print('z=',z)

z = [x for x in z if abs(x) > 4]
print('z=',z)

z = [x for x in z and y for y in z if abs(x) == abs(y)] # This needs to modified
print('z=',z)

Output: Output:

z= [(2-4.79583152j), (2+4.79583152j), 1j]
z= [(2-4.79583152j), (2+4.79583152j)]
Traceback (most recent call last):
  File "sort_complex.py", line 7, in <module>
    z = [x for x in z and y for y in z if abs(x) == abs(y)]
NameError: name 'y' is not defined

I want to get rid of this error and z= [(2-4.79583152j), (2+4.79583152j)] in the output as well in the last case.我想摆脱这个错误和z= [(2-4.79583152j), (2+4.79583152j)]在 output 以及最后一个案例中。

As far as syntax is concerned, the line can be:就语法而言,该行可以是:

z = [(x, y) for x in z for y in z if abs(x) == abs(y)]

However, this will also match up each number with itself, and return both orderings for each pair.但是,这也会将每个数字与其自身进行匹配,并返回每对的两个排序。 To avoid that, we can use enumerate , which gives us the index of each element, then pair them up with only the elements later in the list:为避免这种情况,我们可以使用enumerate ,它为我们提供每个元素的索引,然后将它们与列表后面的元素配对:

z = [
    (x, y)
    for (x_index, x) in enumerate(z)
    for y in z[x_index+1:]
    if abs(x) == abs(y)
]

Finally, using == on floating-point values is problematic, because of rounding;最后,由于四舍五入,在浮点值上使用==是有问题的; we will therefore need to allow a small difference:因此,我们需要允许一个小的差异:

z = [
    (x, y)
    for (x_index, x) in enumerate(z)
    for y in z[x_index+1:]
    if abs(abs(x) - abs(y)) < 0.01
]

Following @sabik's suggestion, I could think of a more compact one-liner:按照@sabik 的建议,我可以想到一个更紧凑的单行代码:

z = [x for x in z for y in z if abs(x) == abs(y) and x != y]
print('z=',z)

And keeping a tolerance (say, 0.0001) for float comparison, this would be并保持浮动比较的公差(比如 0.0001),这将是

z = [x for x in z for y in z if abs(abs(x) - abs(y) < 0.0001) and x != y]
print('z=',z)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM