Tạo một danh sách flowers
sublist trong một danh sách
>>> flowers = ['rose','bougainvillea','yucca','marigold','daylilly','lilly of the valley']
Sau đó,
tôi phải gán cho danh sách thorny
các sublist danh sách flowers
bao gồm các đầu tiên fi ba đối tượng trong danh sách.
Đây là những gì tôi đã cố gắng:
>>> thorny = []
>>> thorny = flowers[1-3]
>>> thorny
'daylilly'
>>> thorny = flowers[0-2]
>>> thorny
'daylilly'
>>> flowers[0,1,2]
Traceback (most recent call last):
File "<pyshell#76>", line 1, in <module>
flowers[0,1,2]
TypeError: list indices must be integers, not tuple
>>> thorny = [flowers[0] + ' ,' + flowers[1] + ' ,' + flowers[2]]
>>> thorny
['rose ,bougainvillea ,yucca']
Làm thế nào tôi có thể nhận được chỉ là 3 đối tượng đầu tiên của hoa danh sách, trong khi duy trì giao diện của một danh sách bên trong một danh sách?
Slice ký hiệu được thực hiện với một dấu hai chấm, không phải là một dấu trừ. –