python-3.x - 在 Python 中对数字使用 de startswith 函数
问题描述
我有一个带有数字和字符的列向量,如下所示:
Data
123456
789101
159482
Airplane
Car
Blue
159874
我只需要过滤数值。
我尝试使用该Data.int.startswith
功能,但我相信这个功能不存在。
谢谢。
解决方案
不确定您到底在问什么,但如果您的意思是要从字符串中过滤掉一个整数列表,您可以执行以下操作:
string = """Data
123456
789101
159482
Airplane
Car
Blue
159874""" #The data you provided
def isInt(s): #returns true if the string is an int
try:
int(s)
return True
except ValueError:
return False
print( [i for i in string.splitlines() if isInt(i)] ) #Loop through the lines in the string, checking if they are integers.
这将返回以下列表:
[123456, 789101, 159482, 159874]
推荐阅读
- javascript - 如何使用 CSS 或 JS 使图像在多个分区上粘贴到所需的长度?
- spartacus-storefront - 用于 ASM 实施参考的 Spartacus SAML 单点登录
- javafx - 在 javafx HtmlEditor 中,java 虚拟键盘输入键不起作用
- ios - AFNetworking 崩溃问题 AFHTTPSessionManager.m ios Objective c
- reactjs - 如何在 Django+React 应用程序中显示外键模型中的特定字段?
- powerbi - 以前所有年份的平均每年
- flutter - 用于空值的空检查运算符 - MaterialApp
- android - 您无法推出此版本,因为它不允许任何现有用户升级新添加的 Apk Play 控制台
- c# - Xamarin Forms ViewModel 绑定/多个绑定对象
- google-analytics - 如果我不直接转到 wix 网站的页面网址,Google 跟踪代码管理器标签不会触发