为什么我不能附加两个列表,然后另存为变量,然后用python打印?

2024-06-01 09:21:50 发布

您现在位置: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)

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


Tags: thetotest列表排序顺序字母all
3条回答

可以使用+运算符将两个列表附加在一起。使用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 + 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)

你会有两种不同的结果。你知道吗

相关问题 更多 >