简体   繁体   中英

Comparing list elements

I make a simple code:

arr =  [4, 9, 5, 3, 2, 10]
kpmp = [] # Empty list to store the comparison

for i in arr:
    if i>0:
        x = 0
        j = i
        while j>=0:
            j-=1
            if arr[i] > arr[j]:
                x+=1
    kpmp.append(x)
print(kpmp)

But, I got this error:

Traceback (most recent call last):
  File "python", line 11, in <module>
IndexError: list index out of range

Which is this line if arr[i] > arr[j]:

The expected output I'd like to print is a list [0, 0, 1, 3, 4, 0]
Explanation:
arr = [4, 9, 5, 3, 2, 10]
1. 4 has nothing to compare so the result is 0
2. 9 > 4 the result is 0
3. 4 < 5 < 9 the result is 1
4. 3 < 4 < 5 < 9 the result is 3
5. 2 < 3 < 4 < 5 < 9 the result is 4
6. Well, 10 is the greatest in the list so the result is 0

I got stuck here, kinda basic knowledge with Python, though.
Thanks for your help!

You are currently using elements of list as indices, which will cause an out of range error if they are greater than the length of your list.

Since arr contains 9 , this will throw an out of range error. Also, you need to define x before your if statement, or else you will get a variable not found error.

Here is a different solution to your problem using a list comprehension and slicing :

x = [4, 9, 5, 3, 2, 10]
final = [sum(k > j for k in x[:i]) for i, j in enumerate(x)]

# [0, 0, 1, 3, 4, 0]

Explanation:

sum(k > j for k in x[:i])

This counts all previous values that are greater than the current value. x[:i] gets all elements before the current element in your list.

It looks like you are trying to use i and j as indices, but they will instead be the elements of the list itself. If you want use indices you have a couple of options:

for i in range(len(arr)):

or

for i, _ in enumerate(arr):

The mistake is evident if you try to print the i in your original code

arr =  [4, 9, 5, 3, 2, 10]
for i in arr:
    print(i)

This will print all elements of the list, each on their own line

4
9
5
3
2
10

For fixing the above code:

  • First you will need to iterate through range of length of list.
  • And other change is moving statement of decreasing of j after comparison rather than before.

You can try as below:

arr =  [4, 9, 5, 3, 2, 10]
kpmp = [] # Empty list to store the comparison
# iterate through length of arr
for i in range(len(arr)):
    if i>0:
        x = 0
        j = i
        while j>=0:
            if arr[i] < arr[j]:
                x+=1
            j-=1 # decrease j after comparison rather than before

    kpmp.append(x)
print(kpmp)

Result:

[0, 0, 1, 3, 4, 0]

Using list comprehension:

You can also try using list comprehension as below:

kmpp = [sum(arr[i] < arr[j] for j in range(i)) for i in range(len(arr))]

There is a mistake in your code

for i in arr:
     print(i)         # will print  4 9 5 3 2 10

This will put every element in arr.

So arr[9] will throw an error as the array size is 6.

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.

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