Python从列表中获取某个字符串

时间:2014-11-27 22:17:03

标签: python string list

我在列表中有这样的信息列表:

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

5 个答案:

答案 0 :(得分:2)

您可以使用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'

答案 1 :(得分: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]

答案 2 :(得分:0)

如果你正在寻找一种不那么特别快速的编码方式,你可以循环播放:

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

答案 3 :(得分:0)

这样做:

from operator import itemgetter
last = map(itemgetter(-1), example)
print(last)

答案 4 :(得分:-1)

要获取列表中列表的最后一个元素,您可以

list[0][len(list[0]) -1]