加入特定索引的列表

Har*_*mer 1 python django list python-2.7

我有一个如下列表:

ingredients = ['apple','cream','salt','sugar','cider']
Run Code Online (Sandbox Code Playgroud)

我想加入此列表以获取字符串,但我想从第二个索引加入到最后一个索引.

得到这个:"salt sugar cider" 列表的长度可能会有所不同.

是否可以使用join函数执行此操作,或者我必须通过循环元素来执行此操作?

ale*_*cxe 9

只需切片列表:

>>> l = ['apple', 'cream', 'salt', 'sugar', 'cider']
>>> ' '.join(l[2:])
'salt sugar cider'
Run Code Online (Sandbox Code Playgroud)

我们没有指定切片的结尾,这意味着它将切片到列表的最后一个元素.