我有这样一个信息列表:
example = [
['68', ' ?', ' 38317', ' 1st-4th', ' 2', ' Divorced', ' ?', ' Not-in-family', ' White', ' Female', ' 0', ' 0', ' 20', ' United-States', ' <=50K'],
['32', ' ?', ' 293936', ' 7th-8th', ' 4', ' Married-spouse-absent', ' ?', ' Not-in-family', ' White', ' Male', ' 0', ' 0', ' 40', ' ?', ' <=50K']
]
又名example[0]
是:
['68', ' ?', ' 38317', ' 1st-4th', ' 2', ' Divorced', ' ?', ' Not-in-family', ' White', ' Female', ' 0', ' 0', ' 20', ' United-States', ' <=50K']
而example[1]
将是:
['32', ' ?', ' 293936', ' 7th-8th', ' 4', ' Married-spouse-absent', ' ?', ' Not-in-family', ' White', ' Male', ' 0', ' 0', ' 40', ' ?', ' <=50K']
我只想拿最后一点,' <=50K'
,我该怎么做?你知道吗
如果您正在寻找一种不是特别快的编码方式,则可以循环:
默认情况下,可以从列表的左侧到右侧为列表中的项目编制索引。索引是指根据项目在列表中的数字位置从列表中获取项目。例如:
如果要从列表末尾选择项目,有多种方法,但最简单的方法如下所示:
把它想象成反向索引。因此,不是从左到右获取项目,而是从右到左获取项目。你知道吗
如果要获取从列表左侧开始的项目,请使用正数;如果要获取从右侧开始的项目,请使用负数。你知道吗
所以你的代码是:
会像这样:
可以使用list comprehension获取所有嵌套列表的最后一个元素:
这将产生
[' <=50k', ' <=50k']
。你知道吗演示:
也可以直接寻址每个嵌套列表并提取最后一个元素:
相关问题 更多 >
编程相关推荐