我正在尝试对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))
答案 0 :(得分:0)
您正在输入字符串:
#Prompts the user to enter an element populating the nums list
for x in range(elements):
nums.append(input("Enter element: "))
您想要整数:
#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)
答案 1 :(得分:-1)
我认为通过索引而不是循环,您可能会更轻松:
x = [3,2,1,6,12,11]
middle = int(len(x)/2)
sorted(x[middle:])
输出:[6, 11, 12]