【发布时间】:2017-05-20 20:31:42
【问题描述】:
问题
我有一个清单,
['apples','oranges','peaches','pear']
我想让列表的前三项自动成为一个单独的变量,例如:
item1 = 'apples'
item2 = 'oranges'
item3 = 'peaches'
我不想要值 pear 的变量,因为它是列表中的第 4 项。
解决方案
我目前正在修改我的旧帖子,我决定修改这篇帖子。
这个问题的所有答案都是准确的并且工作得很好。但是,您可以通过使用它们的索引轻松获取列表中的特定项目,这在某些情况下会更好。
>>> list = ['apples','oranges','peaches','pear']
>>> list[0:3] #This displays items in the list in order from 0-3.
['apples', 'oranges', 'peaches']
>>> list[2] #Value is the 3rd item, as the numbers start from 0 and not 1
'peaches'
【问题讨论】:
-
你的意思是
item1, item2, item3 = itemlist? -
那正在将列表转换为单个变量
-
@khelwood 谢谢,那行得通。我认为这是将变量转换为列表。
-
如果您的列表有 4 个以上的条目会怎样?还是 2,就此而言?
标签: python python-3.x tuples