[英]Python, sorting my list from its original form
I have been searching but haven't found any thread that matches what I'm looking for. 我一直在搜索,但没有找到与我在寻找的匹配的任何线程。 What I'm trying to do, is sorting a list from 3 different options, Chronological(The original list), Alphabetical and Reversed sorting.
我想做的是从3个不同的选项中对列表进行排序,按时间顺序(原始列表),按字母顺序和反向排序。 All of them, I have figured out, for example here is my list:
我已经弄清楚了所有这些,例如,这是我的清单:
movies = ["Star Wars", "Hamilton", "Fight club", "Beck", "Wallander"]
And here's my code: 这是我的代码:
def print_movies():
global movies
j = 0
while j < 1:
print("Hur vill du skriva ut filmerna?")
print("1. Kronologisk\n2. Alfabetisk stigande\n3. Alfabetisk fallande")
choice = input()
if int(choice) == 1:
print("Filmer i samlingen just nu:\n")
for i in movies:
print(i)
j = j+1
elif int(choice) == 2:
print("Filmer i samlingen just nu:\n")
movies.sort()
for i in movies:
print(i)
j = j+1
elif int(choice) == 3:
print("Filmer i samlingen just nu:\n")
movies.sort(reverse=True)
for p in movies:
print(p)
j = j+1
else:
print("Not a valid option, try again")
The sorting and everything works fine, but when I for example press: 2, sort in Alphabetical, it prints out Alphabetical, and when I press: 1 the next time, it doesn't go back to Chronological. 排序和一切工作正常,但是例如当我按:2时,按字母顺序排序,它会按字母顺序打印,而当我下次按:1时,它不会返回到按时间顺序排列。 So the option 2 and 3 works fine, it can sort from highest Alphabetical character to reversed sorting but it wont go back to its original list form, and by that I mean:
因此,选项2和3可以正常工作,它可以从最高字母字符排序到反向排序,但不会回到其原始列表形式,这意味着:
["Star Wars", "Hamilton", "Fight club", "Beck", "Wallander"]
When I press: 1, its still sorted in either option 2 or 3 of which I entered before. 当我按:1时,它仍然按照我之前输入的选项2或3进行排序。
Would really appreciate the help here. 非常感谢您的帮助。 Thanks!
谢谢!
movies.sort()
modifies the list. movies.sort()
修改列表。 so you will lose your original ordering. 因此您将失去原始订单。
Try for m in sorted(movies):
instead. 尝试
for m in sorted(movies):
。
Just make a copy of your list, because movies.sort()
, modifies to original list. 只需复制列表即可,因为
movies.sort()
会修改为原始列表。
copyMovies = movies[:]
Here's an example: 这是一个例子:
>>> movies = ["Star Wars", "Hamilton", "Fight club", "Beck", "Wallander"]
>>> copyMovies = movies[:]
>>> movies.sort()
>>> movies
['Beck', 'Fight club', 'Hamilton', 'Star Wars', 'Wallander']
>>> copyMovies
['Star Wars', 'Hamilton', 'Fight club', 'Beck', 'Wallander']
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.