简体   繁体   English

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

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

I have a list which contains the following string element. 我有一个包含以下string元素的列表。

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

I perform a .split("$") operation and get the following new list. 我执行.split("$")操作并获得以下新列表。

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

I want to be able to store all the integer values from this templist which are at even indexes after the split.I want to return a list of integers. 我希望能够存储此templist列表中的所有整数值,这些整数值在templist后位于偶数索引处。我想返回一个整数列表。

Expected output: [120, 121]

You can split at $ and use a list comprehension with str.isdigit() to extract numbers: 您可以在$处拆分,并使用带有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]]

This will produce a list of lists and convert the "string" numbers into integers. 这将产生一个列表列表,并将“字符串”数字转换为整数。 it only works for positive numbers-strings without sign - with sign you can exchange isdigit() for another function: 它仅适用于带正号的无符号字符串-带符号可以将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]]

To get a flattened list no matter how many strings are in myList : 要获取扁平化列表,无论myList有多少个字符串:

intlist = list(map(int,( d for d in '$'.join(myList).split("$") if isInt(d))))
print(intlist) # [-120, 121, 222, 42]

Updated version: 更新后的版本:

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)

Why not just use re ? 为什么不只是使用re

re is a library for regular expresions in python. re是一个用于python中常规表达式的库。 They help you find patterns. 他们可以帮助您找到模式。

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)

First off we split string with '$' as separator. 首先,我们使用'$'作为分隔符分割字符串。 And then we just iterate through every other result from the new list, convert it into integer and append it to 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]

Do something like this? 像这样吗

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