python - 从 Python 列表中提取数据
问题描述
我有一个字符串列表,我想取它的最后一个“单词”,解释:
这是我的代码:
myList = ["code 53 value 281", "code 53 value 25", ....]
我只想取最后的数字:
myList = ["281", "25", ....]
谢谢你。
解决方案
让我们分解你的问题。
所以首先,你有一个字符串列表。您知道每个字符串都会以某种数值结尾,您想将其取出并将其存储在列表中。基本上,您想要摆脱除最后一个数值之外的所有内容。
用代码来编写它,我们需要迭代该列表,用空格字符分割每个字符串' '
,然后从该集合中获取最后一个单词,并将其存储在列表中。
有很多方法可以做到这一点,但最简单的是列表理解。
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"
推荐阅读
- reactjs - 如何在 React-Native React Navigation 5 中向下滚动时制作从透明到不透明颜色的动画标题?
- linux - 从一个文件创建多个名称与模式匹配的文件
- swiftui - 在 NavigationLink 的嵌套 NavigationView 中列出 CoreData 对象的正确方法
- asp.net - 如何使用 XDT 在 web.config 中查找元素,然后将其更改为 nuget deploy
- .net - 带有 Windows 服务的架构模式
- aws-lambda - AWS API Gateway:CORS 和空事件对象
- postgresql - 按子 ID 过滤父级
- javascript - 我怎样才能让这个地球可视化(svg)能够响应不同的屏幕尺寸?
- java - Qt for Android 和 ARCore 应用程序冲突
- docker - Docker Swarm - 创建新容器时的秘密问题