gpt4 book ai didi

Python 从列表中获取特定字符串

转载 作者:行者123 更新时间:2023-12-01 04:56:54 25 4
gpt4 key购买 nike

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

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 获取所有嵌套列表的最后一个元素:

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

关于Python 从列表中获取特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27179381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com