为什么我不能附加 2 个列表然后另存为变量然后在 python 中打印?



我是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)

两者都导致 [无],但我想要的是附加 2 个列表,按字母顺序排序,然后打印结果。这不是为了什么重要的事情,只是想熟悉python。

要将两个列表附加到一起,您需要执行以下操作:

test = songs + artists

因为这行:

[songs.append(artists)]

将整个artists列表作为单个元素添加到songs列表的末尾,除此之外append()返回None,所以你最终会得到一个看起来像这样的列表:

[None]

请花一些时间阅读文档,了解追加到列表和连接两个列表之间的区别,并记住准确检查操作返回的值 - 以避免append()sort()和其他返回None

的意外。

您可以先将它们组合在一起,然后只需排序一次:

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 = sorted(songs + 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 = sorted(songs) + sorted(artists)
print(test)

您将有 2 种不同的结果。

您可以将两个列表与+运算符一起追加。使用sorted()返回从给定元素排序的新列表。

Sorted(list1 + list2)为您提供了所有元素的新排序列表。

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"]
combined = sorted(songs+artists)
>>> combined
['All Along the Watchtower', 'Deep Purple', 'Jimi Hendrix', 'Led Zepplin', 'Protoje', 'RTJ', 'Riders on the Storm', 'Stairway to Heaven', 'The Doors', 'Wu-Tang']

这是因为你在做什么

test = [songs.append(artists)]

您正在执行追加。将其更改为在之前附加,然后执行

songs.append(artists)
test = [songs]

相关内容

最新更新