**程序的功能:**输入一个随机的数组,然后随机插入一个数字之后对数组进行排序。
这次遇到了一个数据类型转换的问题。
if __name__ == '__main__':
n = int(input("Please Input the D is:\n"))
a = []
for i in range(n):
a.append([])
if i == n-1:
a[i] = 0
else:
a[i].append(float(input("Please input the Number:")))
print("Initial List:")
for i in range(n):
print(a[i])
number = int(input("\n插入一个数字:\n"))
end = a[n-2]
if number > end:
a[n-1] = number
else:
for i in range(n-1):
if a[i] > number:
tem1 = a[i]
a[i] = number
for j in range(i + 1, n):
tem2 = a[j]
a[j] = tem1
tem1 = tem2
break
print('排序后的列表为:')
for i in range(n):
print (a[i])
print("插入新数后的列表为:")
for i in range(n):
print (a[i])
# 排序
for i in range(n):
for j in range(i + 1, n):
if a[i] > a[j]:
temp3 = a[i]
a[i] = a[j]
a[j] = temp3
print("排序后的列表为:")
for i in range(n):
print(a[i])
第一次输出结果提示:
Traceback (most recent call last):
File "H:/Python/39.py", line 17, in <module>
if number > end:
TypeError: '>' not supported between instances of 'int' and 'list'
根据提示将end = a[n-2]
改为end = int(a[n-3])
以后出来得第二次提示为
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
之后将end = a[n-2]
改为end = a[-3]
同时在下面加了一行输出end
的类型,出来的结果是
<class 'list'>
Traceback (most recent call last):
File "H:/Python/39.py", line 18, in <module>
if number > end:
TypeError: '>' not supported between instances of 'int' and 'list'
但是我在shell中运行的
>>> a = [2, 5, 6, 9, 7]
>>> a[-2]
9
>>> type(a)
<class 'list'>
>>> b = a[-2]
>>> b
9
>>> type(b)
<class 'int'>
>>> c = a[-3]
>>> type(c)
<class 'int'>
这是什么鬼啊(抓头发!)然后我就顺着一直往上查看a[]的输出类型,从最开始的for循环输入开始就一直是list
的类型。所以将
a[i].append(float(input("Please input the Number:")))
改为
a[i] = int(input("Please input the Number:"))
然后就可以正常输出了。
Ps:当然排序的时候直接用Python中的.sort()即可。