如何在Python中创建一个列表,该列表将产生以下结果[]

2024-05-16 16:25:49 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个关于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]

请问为什么我没有得到预期的输出


Tags: https元素列表new链接airfiregames
3条回答

以下是我在您提供的链接中执行的代码:

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]

因此,它将预期值显示为[]

第9个元素是['water'、'air'、'fire'、'earth'](包括在内),第12个元素是“code”(python中不包括它) 所以结果是[[水”,“空气”,“火”,“地球”,“游戏”,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]

相关问题 更多 >