我是python新手,还在学习基本的命令和东西。我现在正在制作和编辑列表,我正在尝试按字母顺序排序2个列表,然后附加它们,最后打印它们。我编写了以下代码:
songs = ["Stairway to Heaven", "All Along the Watchtower", "Riders on the Storm"]
artists = ["Deep Purple", "Wu-Tang", "Protoje", "RTJ", "The Doors", "Jimi Hendrix", "Led Zepplin"]
songs.sort()
artists.sort()
test = [songs.append(artists)]
print(test)
我也试过了
songs = ["Stairway to Heaven", "All Along the Watchtower", "Riders on the Storm"]
artists = ["Deep Purple", "Wu-Tang", "Protoje", "RTJ", "The Doors", "Jimi Hendrix", "Led Zepplin"]
test = [songs.append(artists)]
test.sort()
print(test)
两个结果都是[None],但我想要的是附加两个列表,按字母顺序排序,然后打印结果。这不是为了什么重要的事情,只是为了熟悉python。你知道吗
可以使用
+
运算符将两个列表附加在一起。使用sorted()
返回从给定元素排序的新列表。你知道吗Sorted(list1 + list2)
提供所有元素的新排序列表。你知道吗要将两个列表附加在一起,需要执行以下操作:
因为这条线:
将整个
artists
列表作为单个元素添加到songs
列表的末尾,除此之外append()
还返回None
,因此您只需得到如下列表:请花一些时间阅读文档,了解将附加到列表和将两个列表串联在一起的区别,并记住检查操作返回的值是什么-以避免对
append()
、sort()
和其他返回None
的操作产生意外。你知道吗您可以先将它们合并,然后只排序一次:
或者先将它们排序,然后再合并:
你会有两种不同的结果。你知道吗
相关问题 更多 >
编程相关推荐