pizzas = ["hawai","salame","vegetable","capriciosa","new york"]
for pizza in pizzas:
print("I like " + pizza.title() + " pizza!")
print("\n" + "The first three pizzas in the list are: " + str(pizzas[0:3]))
print("\n" + "The last three pizzas in the list are: " + str(pizzas[-1:-3]))
Run Code Online (Sandbox Code Playgroud)
我明白了:
I like Hawai pizza!
I like Salame pizza!
I like Vegetable pizza!
I like Capriciosa pizza!
I like New York pizza!
The first three pizzas in the list are: ['hawai', 'salame', 'vegetable']
The last three pizzas in the list are: []
Run Code Online (Sandbox Code Playgroud)
我很困惑.是不是-1表示列表中的最后一个元素?我正在索引[start:stop]所以不应该打印我的最后3项?我究竟做错了什么 ?
您应该使用pizzas[-3:],以便您start是列表末尾的第三个元素,并且您end是列表的最后一个元素.
pizzas = ["hawai","salame","vegetable","capriciosa","new york"]
for pizza in pizzas:
print("I like " + pizza.title() + " pizza!")
print("\nThe first three pizzas in the list are: " + str(pizzas[:3]))
print("\nThe last three pizzas in the list are: " + str(pizzas[-3:]))
Run Code Online (Sandbox Code Playgroud)
默认步长为 1,因此从 -1 到 -3 步长为 1 会返回一个空切片。您可以明确地将步骤指示为 -1,但这会颠倒项目的顺序:
>>> pizzas[-1:-3:-1]
['new york', 'capriciosa'] # -3 excluded
Run Code Online (Sandbox Code Playgroud)
但是,要获得最后三个项目,您想要的是 pizza[-3:]