首页 > 解决方案 > 从 Python 列表中提取数据

问题描述

我有一个字符串列表,我想取它的最后一个“单词”,解释:

这是我的代码:

myList = ["code 53 value 281", "code 53 value 25", ....]

我只想取最后的数字:

myList = ["281", "25", ....]

谢谢你。

标签: pythonlist

解决方案


让我们分解你的问题。

所以首先,你有一个字符串列表。您知道每个字符串都会以某种数值结尾,您想将其取出并将其存储在列表中。基本上,您想要摆脱除最后一个数值之外的所有内容。

用代码来编写它,我们需要迭代该列表,用空格字符分割每个字符串' ',然后从该集合中获取最后一个单词,并将其存储在列表中。

有很多方法可以做到这一点,但最简单的是列表理解。

myList = ["Hey 123", "Hello 456", "Bye 789"] # we want 123, 456, 789

myNumericList = [x.split(' ')[-1] for x in myList]
# for x in myList is pretty obvious, looks like a normal for loop
# x.split(' ') will split the string by the space, as an example, "Hey 123" would become ["Hey", "123"]
# [-1] gets the last element from the collection

print(myNumericList) # "123", "456", "789"

推荐阅读