Python从lis中获取某个字符串

2024-10-04 15:19:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个信息列表:

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',我该怎么做?你知道吗


Tags: in信息列表examplenotfamilymalefemale
3条回答

如果您正在寻找一种不是特别快的编码方式,则可以循环:

new_list = []
for smaller_list in big_list:
     new_list.append(smaller_list[-1])

默认情况下,可以从列表的左侧到右侧为列表中的项目编制索引。索引是指根据项目在列表中的数字位置从列表中获取项目。例如:

myList = [1,2,3,4,5,6]
myList[0] # This would give me the 1st item of the list; the number 1
myList[1] # would give me the number 2 and so on....

如果要从列表末尾选择项目,有多种方法,但最简单的方法如下所示:

myList[-1] # this would get me the last item of the list; 6 
myList[-2] # would get the second to last item
myList[-3] # would get the third to last item
myList[-4] # would get the fourth to last item

把它想象成反向索引。因此,不是从左到右获取项目,而是从右到左获取项目。你知道吗

如果要获取从列表左侧开始的项目,请使用正数;如果要获取从右侧开始的项目,请使用负数。你知道吗

所以你的代码是:

['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']

会像这样:

lastItem = list_of_information[0][-1]

可以使用list comprehension获取所有嵌套列表的最后一个元素:

[sublist[-1] for sublist in example]

这将产生[' <=50k', ' <=50k']。你知道吗

演示:

>>> 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'],
... ]
>>> [sublist[-1] for sublist in example]
[' <=50K', ' <=50K']

也可以直接寻址每个嵌套列表并提取最后一个元素:

>>> example[0][-1]
' <=50K'
>>> example[1][-1]
' <=50K'

相关问题 更多 >

    热门问题