繁体   English   中英

获取列表中字符串的最后一部分

[英]Get the last part of a string in a list

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

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

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

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

我希望能够存储此templist列表中的所有整数值,这些整数值在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]

更新后的版本:

import re
myList = ['120$My life cycle 3$121$My daily routine 2']
myList = myList[0].split('$')
numbers = []
for i in range(0,len(myList),2):
        temp = re.findall(r'\d+', myList[i])[0]
        numbers.append(temp)
'''
.finall() returns list of all occurences of a pattern in a given string.
The pattern says map all digits in the string. If they are next to each
other count them as one element in final list. We use index 0 of the 
myList as thats the string we want to work with.
'''
results = list(map(int, numbers)) # this line performs an int() operation on each of the elements of numbers.
print(results)

为什么不只是使用re

re是一个用于python中常规表达式的库。 他们可以帮助您找到模式。

import re
myList = ['120$My life cycle 3$121$My daily routine 2']
numbers = re.findall(r'\d+$', myList[0]) 
'''
.finall() returns list of all occurences of a pattern in a given string.
The pattern says map all digits in the string. If they are next to each
other count them as one element in final list. We use index 0 of the 
myList as thats the string we want to work with.
'''
results = list(map(int, numbers)) # this line performs an int() operation on each of the elements of numbers. 
print(results)

首先,我们使用'$'作为分隔符分割字符串。 然后,我们仅遍历新列表中的所有其他结果,将其转换为整数并将其附加到结果中。

myList = ['120$My life cycle 3$121$My daily routine 2']
myList = myList[0].split('$')
results = []
for i in range(0,len(myList),2):
    results.append(int(myList[i]))
print(results)
# [120, 121]

像这样吗

a = ['100$My String 1A$290$My String 1B']
>>> for x in a:
...   [int(s) for s in x.split("$") if s.isdigit()]
...
[100, 290] 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM