小编Rob*_*ntz的帖子

列表中的子列表

创建了一个列表 flowers

>>> flowers = ['rose','bougainvillea','yucca','marigold','daylilly','lilly of the valley']
Run Code Online (Sandbox Code Playgroud)

然后,

我必须分配列表thorny的子列表,该列表包含列表flowers中的前三个对象.

这是我试过的:

>>> 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']
Run Code Online (Sandbox Code Playgroud)

如何保持列表花的前3个对象,同时保持列表中列表的外观?

python list sublist

8
推荐指数
3
解决办法
5万
查看次数

标签 统计

list ×1

python ×1

sublist ×1