[英]Finding all elements greater than current element in a list
If I have an array in Python in which all of the elements have different values, eg [1,4,6,2,10,3,5]
, is there a way to find the total number of values in the list that are greater than the current index?如果我在 Python 中有一个数组,其中所有元素都有不同的值,例如[1,4,6,2,10,3,5]
,有没有办法找到列表中的值的总数大于当前指数?
So for example, using the above list of length 7, the result I'd like to get is another list of length 7 which looks like [6,3,1,5,0,4,2]
.因此,例如,使用上面长度为 7 的列表,我想要得到的结果是另一个长度为 7 的列表,它看起来像[6,3,1,5,0,4,2]
。 I was having trouble trying to loop through the list (the code I tried to use is below)我在尝试遍历列表时遇到了麻烦(我尝试使用的代码如下)
for i in data:
count = np.sum(data > data[i])
N[i]=count
where data
is the array containing all the pertaining values and N
is an np.zeros
list of the same length as data其中data
是包含所有相关值的数组, N
是与 data 长度相同的np.zeros
列表
Here is my suggestion:这是我的建议:
We sort the original list (l) and save it in a new list m.我们对原始列表 (l) 进行排序,并将其保存在新列表 m 中。 We create a new list (k) where we save the count of elements that are found on the right of the position of each element in m.我们创建一个新列表 (k),在其中保存在 m 中每个元素的 position 右侧找到的元素计数。 See below:见下文:
l=[1,4,6,2,10,3,5]
m=sorted(l)
#[1, 2, 3, 4, 5, 6, 10]
k=[]
for i in l:
k.append(len(m)-m.index(i)-1)
>>> print(k)
[6, 3, 1, 5, 0, 4, 2]
You were very close.你非常亲近。 for i in data
iterates through each element , not the indices as in Java/C. for i in data
遍历每个元素,而不是 Java/C 中的索引。
Use range(len(data))
instead.使用range(len(data))
代替。
import numpy as np
data = np.array([1,4,6,2,10,3,5])
out = np.array([0]*7)
for i in range(len(data)):
count = np.sum(data > data[i])
out[i] = count
print(out) # [6 3 1 5 0 4 2]
Another way to write the loop is to use enumerate()
, which returns an iterator of pairs of (indices, elements).编写循环的另一种方法是使用enumerate()
,它返回一对(索引,元素)的迭代器。
for i, x in enumerate(data):
count = np.sum(data > x)
out[i] = count
Something like this?像这样的东西?
list = [1,4,6,2,10,3,5]
list2 = []
v = len(list)
for x in list:
if x > v:
pass
else:
list2.append(x)
print(list2)
EDIT ¯\_(ツ)_/¯
(To see the total number of elements greater than the current element) EDIT ¯\_(ツ)_/¯
(查看大于当前元素的元素总数)
list = [1,4,6,2,10,3,5]
list2 = []
v = len(list)
total = 0
for x in list:
if x > v:
pass
else:
list2.append(x)
for y in list2:
total += 1
list2 = str(list2).replace('[', '')
list2 = list2.replace(']', '')
print("Now - " + list2 + ", in total of " + str(total) + " numbers ;)")
Output - Output -
Now - 1, 4, 6, 2, 3, 5, in total of 6 numbers ;)
Alternatively, you can do it by using vectorize
as follows:或者,您可以通过使用vectorize
来做到这一点,如下所示:
>>> data = np.array( [1,4,6,2,10,3,5] )
>>> np.vectorize(lambda a, b : np.sum(a>b), excluded = [0] )(data, data)
array([6, 3, 1, 5, 0, 4, 2])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.