Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 排序列表的后半部分在某些情况下不起作用_Python_List_Sorting - Fatal编程技术网

Python 排序列表的后半部分在某些情况下不起作用

Python 排序列表的后半部分在某些情况下不起作用,python,list,sorting,Python,List,Sorting,我试图对python列表的后半部分进行排序。在某些情况下有效,但在某些情况下无效。 这是一个程序似乎失败的案例: 6要素 [3,2,1,6,12,11] 这是我的代码: #Initalizes the lists and prompts the user for the number of elements in the list nums = [] original = [] sorter = [] elements = int(input("Please enter number of el

我试图对python列表的后半部分进行排序。在某些情况下有效,但在某些情况下无效。 这是一个程序似乎失败的案例: 6要素
[3,2,1,6,12,11]

这是我的代码:

#Initalizes the lists and prompts the user for the number of elements in the list
nums = []
original = []
sorter = []
elements = int(input("Please enter number of elements in list: "))

#Prompts the user to enter an element populating the nums list
for x in range(elements):
    nums.append(input("Enter element: "))

#Copies the nums list to original and sorter to modify the list for sorting
original = nums.copy()
sorter = nums.copy()

#Removes the first half of sorter and the second half of nums
for x in range(int(elements/2)):
    nums.pop()
    sorter.pop(0)

#Sorts the sorter list
sorter.sort()

#Prints the original list as well as the concatonated nums and sorter list
print("You entered: " + str(original))
print("Sorted: " + str(nums + sorter))

我认为通过索引而不是循环,您可能会更轻松:

x=[3,2,1,6,12,11]
中间=整数(len(x)/2)
已排序(x[中间:)

输出:
[6,11,12]
您正在输入字符串:

#Prompts the user to enter an element populating the nums list
for x in range(elements):
    nums.append(input("Enter element: "))
您想要ints:

#Prompts the user to enter an element populating the nums list
for x in range(elements):
    nums.append(int(input("Enter element: ")))
那么你的代码就可以正常工作了

尽管您可能想考虑使用拼接和listcomp来实现更简单的方法:

elements = int(input("Please enter number of elements in list: "))
nums = [int(input("Enter element: ")) for _ in range(elements)]

sorted_nums = nums[:elements // 2] + sorted(nums[elements // 2:])

print("You entered:", nums)
print("Sorted:", sorted_nums)

您能提供和输入以及所需的输出吗?您正在排序字符串,而不是数字<代码>已排序(['6',12',11'])==['11',12',6'],而不是
['6',11',12']
或(您似乎期望的)
[6,11,12]
。另外,您能说说当列表中的项目数为奇数时会发生什么情况吗?