[英]Why can't I append 2 lists then save as a varible then print in 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] 但我想要的是附加 2 個列表,按字母順序對它們進行排序,然后打印結果。 它不是為了任何重要的事情,只是想熟悉 python。
要將兩個列表附加在一起,您需要執行以下操作:
test = songs + artists
因為這一行:
[songs.append(artists)]
將整個artists
列表作為單個元素添加到songs
列表的末尾,除了append()
返回None
,因此您最終會得到一個如下所示的列表:
[None]
請花一些時間閱讀文檔,了解附加到列表和連接兩個列表之間的區別,並記住檢查操作返回的確切值 - 避免append()
、 sort()
和其他返回的意外None
。
那是因為你在做什么
test = [songs.append(artists)]
你在做一個追加。 將其更改為 append before 然后執行
songs.append(artists)
test = [songs]
您可以使用+
運算符附加兩個列表。 使用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']
您可以先將它們組合起來,然后只排序一次:
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 種不同的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.