簡體   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