簡體   English   中英

從python中的字符串中獲取特定的子字符串

[英]Take a specific sub-string from a string in python

如何在pythonTrain_level1存儲lst1 = [26.7,8.2,13.7,8.6,16]

Train_level1 = ['1_Rehana_Karim_F49_850_GL=26.7','43_G.M.Alauddin Azad_M42_940_GL=8.2','110_Ronojeet_Bishwash_M47_940_GL=13.7','112_Mustafizur_Rahman_M60_850_GL=8.6','123_Farida_Yeasmin_F55_940_GL=16']

同樣,如何在pythonTrain_level2存儲lst2 = [11.5,12.9,9.2]

Train_level2 = ['S140_M75_GL=11.5-850LEDFon_F=110.jpg', 'S85_F56_GL=12.9-940LEDFon_F=105.jpg', 'S108_M71_GL=9.2-850LEDFon_F=100.jpg']

對於Train_level ,您需要獲取=后面的數字,因此我們在字符串列表上使用split()將其按=字符進行拆分,並獲取索引為0的第二個字符串:

lst1 = [float(train.split('=')[1]) for train in Train_level1]

對於Train_level2 ,它是相似的,除了我們需要進行兩次拆分-首先通過=並獲取第二個字符串(索引1),然后通過-並獲取第一個字符串(索引0):

lst2 = [float(train.split('=')[1].split('-')[0]) for train in Train_level2]

我們在結果上使用float() ,因為split返回一個字符串,但輸出是數字列表,而不是字符串。 float會將包含數字的十進制字符串轉換為浮點數。

您可以使用正則表達式解析數字:

import re

Train_level1 = ['1_Rehana_Karim_F49_850_GL=26.7',
                '43_G.M.Alauddin Azad_M42_940_GL=8.2',  
                '110_Ronojeet_Bishwash_M47_940_GL=13.7',
                '112_Mustafizur_Rahman_M60_850_GL=8.6',
                '123_Farida_Yeasmin_F55_940_GL=16']

Train_level2 = ['S140_M75_GL=11.5-850LEDFon_F=110.jpg', 
                'S85_F56_GL=12.9-940LEDFon_F=105.jpg', 
                'S108_M71_GL=9.2-850LEDFon_F=100.jpg']


def parseIt(data):
    p1 = r"=(\d+\.?\d*)" # find '=' followed numbers followed by optional '.' + more numbers
    return [float(x[0]) for x in (re.findall(p1,y) for y in data) if x] 


print(parseIt(Train_level1))
print(parseIt(Train_level2))

輸出:

[26.7, 8.2, 13.7, 8.6, 16.0]
[11.5, 12.9, 9.2]

list-comp和regex是相同的,因此我為此創建了一個函數。 他們將正則表達式應用於每個列表元素。 每個列表只有一個=99.99元素,因此我們將其中一個元素更改為浮動元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM