繁体   English   中英

IndexError:列表索引超出范围python排序数组

[英]IndexError: list index out of range python sorting array

我编写此代码来对数组的元素进行排序,但是我在if(a [i]> a [j])中得到了此错误行9,IndexError:列表索引超出范围用于对数组元素进行排序的相同逻辑与java一起工作或c正确。 帮助我找到为什么这在python中发生。 这是由于python语法还是其他原因

from array import *
a=[]
n=int(input("enter number of elements:"))
for i in range(0,n):
    b=input("enter element")
    a.append(b)
for i in range(0,n):
    for j in range(i+1,n):
        if(a[i]>a[j]):
            temp=a[i]
            a[i]=a[j]
            a[j]=temp
print("sorted")
for i in range(0,n-1):
    print(a[i])
    print(a[n-1])

首先,您不需要自己编写列表排序方法,而python会为您完成。 第二个不需要第三个临时变量在python中的两个变量之间交换值,只需a,b = b,a将在a和b之间交换值

a=[1,5,4,7,8,3,5,4]
for i in range(len(a)):
    for j in range(i+1,len(a)):
        if a[i]>a[j]:
            a[i],a[j]=a[j],a[i]

print(a)

上面的代码按升序排序。 对于降序,将>更改为<。 最好使用内置列表排序方法和sorted函数对任何列表进行排序。

这是您当前代码的一些改进:

a =[]
n = int(input("enter number of elements: "))

for i in range(0, n):
    b=input("enter element: ")
    a.append(b)
# You can also, use:
# for i in range(len(a))
for i in range(0, n):
    # Same:
    # for j in range(i+1, len(a))
    for j in range(i+1, n):
        # Be aware:
        # if the data passed to the list a cannot be converted
        # into an integer, this code will throw a ValueError exception
        if int(a[i]) > int(a[j]):
            # You don't need to create a 'temp' variable
            # Python can handle it dynamically
            a[i], a[j] = a[j], a[i]

            print("Sorted")
            print(" ".join(a))

演示:

enter number of elements: 4
enter element: 5
enter element: 1
enter element: 4
enter element: 3
Sorted
1 5 4 3
Sorted
1 4 5 3
Sorted
1 3 5 4
Sorted
1 3 4 5

PS:我建议您使用Python内置的sorted()list.sort() ,它是就地列表排序

暂无
暂无

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

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