python - 获取列表中字符串的最后一部分
问题描述
我有一个包含以下string
元素的列表。
myList = ['120$My life cycle 3$121$My daily routine 2']
我执行.split("$")
操作并获得以下新列表。
templist = str(myList).split("$")
我希望能够存储templist
拆分后位于偶数索引处的所有整数值。我想返回一个整数列表。
Expected output: [120, 121]
解决方案
您可以在 $处拆分并使用列表推导来str.isdigit()
提取数字:
mylist = ['120$My life cycle$121$My daily routine','some$222$othr$text$42']
# split each thing in mylist at $, for each split-result, keep only those that
# contain only numbers and convert them to integer
splitted = [[int(i) for i in p.split("$") if i.isdigit()] for p in mylist]
print(splitted) # [[120, 121], [222, 42]]
这将生成一个列表列表并将“字符串”数字转换为整数。它仅适用于没有符号的正数字符串 - 有符号您可以交换isdigit()
另一个函数:
def isInt(t):
try:
_ = int(t)
return True
except:
return False
mylist = ['-120$My life cycle$121$My daily routine','some$222$othr$text$42']
splitted = [[int(i) for i in p.split("$") if isInt(i) ] for p in mylist]
print(splitted) # [[-120, 121], [222, 42]]
无论有多少字符串,要获得一个扁平列表myList
:
intlist = list(map(int,( d for d in '$'.join(myList).split("$") if isInt(d))))
print(intlist) # [-120, 121, 222, 42]
推荐阅读
- sql - 数据库理解
- excel - 除法结果为0
- curl - virtualbox ping,telnet 工作但不卷曲
- python - pandas 按分位数过滤会产生一个空集
- c# - 如何使用 c# 获取 Instagram 故事集锦?
- javascript - 从 html 脚本标签(内联)访问 webpack 捆绑的 javascript 文件中的变量
- laravel - 如何在laravel中获取实时数据
- git - 在上一次提交合并 master 之后将分支合并到 master 然后将其还原
- arcgis-js-api - ArcGIS API 4.x 中用于更改底图的菜单
- r - 如何在格子面板中添加多条垂直线?