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?
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]
. 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
Here is my suggestion:
We sort the original list (l) and save it in a new list 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. 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.
Use range(len(data))
instead.
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).
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)
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 -
Now - 1, 4, 6, 2, 3, 5, in total of 6 numbers ;)
Alternatively, you can do it by using vectorize
as follows:
>>> 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])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.