簡體   English   中英

如何在 Python 中創建將產生以下結果的列表 []

[英]How to create a list in Python that will yield the following result []

這是一個關於coursera實踐過度的問題。

使用 new_lst 的第 9 到第 12 個元素(共四項)創建一個新列表,並將其分配給變量 sub_lst。

問題鏈接: https : //runestone.academy/runestone/books/published/fopp/Sequences/TheSliceOperator.html列表中的最后一個問題。

我的代碼怎么樣

new_lst = ["computer", "luxurious", "basket", "crime", 0, 2.49, "institution", "slice", "sun", 
["water", "air", "fire", "earth"], "games", 2.7, "code", "java", ["birthday", "celebration", 1817, 
"party", "cake", 5], "rain", "thunderstorm", "top down"]
new_lst = new_lst[9:12]
sub_lst = new_lst
print(sub_lst)

我的輸出:

[['water', 'air', 'fire', 'earth'], 'games', 2.7]

但這是預期的輸出:

['sun', ['water', 'air', 'fire', 'earth'], 'games', 2.7]

請問為什么我沒有得到預期的輸出?

您需要從 8 開始索引,因為第 9 個元素位於索引 8。

new_lst = ["computer", "luxurious", "basket", "crime", 0, 2.49, "institution", "slice", "sun", ["water", "air", "fire", "earth"], "games", 2.7, "code", "java", ["birthday", "celebration", 1817, "party", "cake", 5], "rain", "thunderstorm", "top down"]

sub_lst=new_lst[8:8+4]

結果輸出將是 -

['sun', ['water', 'air', 'fire', 'earth'], 'games', 2.7]

你的第 9 個元素是 ['water', 'air', 'fire', 'earth'] (它被包括在內)而第 12 個元素是“代碼”(它被排除在 python 中)所以結果是 [['water', '空氣', '火', '地球'], '游戲', 2.7]

如果你對列表的第 9 到 12 項做一個簡單的輸出

item_count = 0
for item in new_lst:
    item_count += 1
    if 9<=item_count<=12:
        print(str(item_count)+" "+str(item))

你得到輸出

9 sun
10 ['water', 'air', 'fire', 'earth']
11 games
12 2.7

這不是一個空列表。

要獲取第 9 到第 12 項的子列表,請使用基於從 0 開始的索引從 8 開始並以 12 結束的切片,因為最后一項不包含在輸出切片中。

sub_lst = new_lst[8:12]

打印為

print(sub_lst)
['sun', ['water', 'air', 'fire', 'earth'], 'games', 2.7]

這是我在您提供的鏈接中執行的代碼:

new_lst = ["computer", "luxurious", "basket", "crime", 0, 2.49, "institution", "slice", "sun", ["water", "air", "fire", "earth"], "games", 2.7, "code", "java", ["birthday", "celebration", 1817, "party", "cake", 5], "rain", "thunderstorm", "top down"]
sub_lst = new_lst[8:12]
print(sub_lst)

您編寫的代碼中的這一行,您已將 new_lst 的值更新為僅 4 個元素。

new_lst = new_lst[9:12]

因此,它將預期值顯示為 []。

我認為您分配的問題超出了所提出的問題,這是解決方案

new_lst = ["computer", "luxurious", "basket", "crime", 0, 2.49, "institution", "slice", "sun", ["water", "air", "fire", "earth"], "games", 2.7, "code", "java", ["birthday", "celebration", 1817, "party", "cake", 5], "rain", "thunderstorm", "top down"]
sub_lst = new_lst[8:12]

只需執行“sub_lst = new_lst[8:12]”在sub_lst 中分配剛剛切片的列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM