简体   繁体   English

如何检查列表(或数组)上的条件,然后在Python中根据该条件对元素进行排序

[英]How to check a condition on a list (or array) and then sort the elements based on that condition in Python

I have a list of complex numbers with n elements, I want to check that how many of the elements are real (the imaginary part is zero) and then sort my list in a way that it starts with the real numbers. 我有一个包含n个元素的复数列表,我想检查有多少元素是真实的(虚部是零),然后以一个以实数开头的方式对我的列表进行排序。

For example for the list below: 例如,对于以下列表:

a = [ 7 + 0j, -2 + 3j, -2 - 3j, 5 + 6j, 5 - 6j, -1+ 0j, -8 + 4j, -8 - 4j]

two elements are real ( first element and sixth element) I want to know that I have 2 real elements in my list and then I want to have a sort like below that starts with real numbers and the other elements remains unchanged: 两个元素是真实的(第一个元素和第六个元素)我想知道我的列表中有2个真实元素,然后我想要一个类似下面的类型,以实数开头,其他元素保持不变:

b = [ 7 + 0j, -1+ 0j, -2 + 3j, -2 - 3j, 5 + 6j, 5 - 6j, -8 + 4j, -8 - 4j]

How can I do that? 我怎样才能做到这一点? Thanks 谢谢

Python has a sorted function that takes a key argument. Python有一个带有key参数的sorted函数。

The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes. key参数的值应该是一个函数,它接受一个参数并返回一个用于排序的键。

You can sort based on a lambda function that checks the presence of non zero imaginary component. 您可以基于lambda函数进行排序,该函数检查是否存在非零虚部。

a = [ 7 + 0j, -2 + 3j, -2 - 3j, 5 + 6j, 5 - 6j, -1+ 0j, -8 + 4j, -8 - 4j]
sorted(a, key = lambda x: x.imag != 0) 
#Output: [(7+0j), (-1+0j), (-2+3j), (-2-3j), (5+6j), (5-6j), (-8+4j), (-8-4j)]

You can sort the numbers by comparing their imaginary part against zero. 您可以通过将它们的虚部与零进行比较来对数字进行排序。 Those with 0's will come first, remaining numbers will be unchanged in their order. 那些0的人将首先出现,其余的数字将保持不变。

a = sorted(a, key=lambda x:x.imag!=0)
print(a)

Outputs 输出

[(7+0j), (-1+0j), (-2+3j), (-2-3j), (5+6j), (5-6j), (-8+4j), (-8-4j)]

To get number of such entries use 要获得此类条目的数量

sum(x.imag == 0 for x in a)

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

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