首页 > 解决方案 > 获取列表中字符串的最后一部分

问题描述

我有一个包含以下string元素的列表。

myList = ['120$My life cycle 3$121$My daily routine 2']

我执行.split("$")操作并获得以下新列表。

templist = str(myList).split("$")

我希望能够存储templist拆分后位于偶数索引处的所有整数值。我想返回一个整数列表。

Expected output: [120, 121]

标签: python

解决方案


您可以在 $处拆分并使用列表推导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]

推荐阅读