我有一個字串串列,如下所示:
Loops = ['Loop 0 from point number 0 to 965',
'Loop 1 from point number 966 to 1969',
'Loop 2 from point number 1970 to 2961']
我正在嘗試從上面的字串串列中獲取點號的范圍。
例如:LoopStart1 = 0, LoopEnd1 = 965, LoopStart2 = 966, LoopEnd2 = 1969
我可以想象使用 for 回圈或字串切片來做到這一點,但是我應該如何/使用哪些命令專門從這些字串串列中獲取點號(整數)?因為每個數字都有不同的長度。
提前致謝!
uj5u.com熱心網友回復:
你可以用regex它來做。然后創建一個字典來存盤所有值:
import re
Loops = ['Loop 0 from point number 0 to 965',
'Loop 1 from point number 966 to 1969',
'Loop 2 from point number 1970 to 2961']
d = {}
for index, value in enumerate(Loops):
m = re.findall(r'\d to \d ', value)
m = [i.split('to') for i in m]
d[f'LoopStart{index 1}'] = int(m[0][0])
d[f'LoopEnd{index 1}'] = int(m[0][-1])
print(d)
輸出:
{'LoopStart1': 0, 'LoopEnd1': 965, 'LoopStart2': 966, 'LoopEnd2': 1969, 'LoopStart3': 1970, 'LoopEnd3': 2961}
解釋:
此行獲取該回圈的索引和專案。即index = 0,1,2...和value = 'Loop 0 from...', 'Loop 1 from ....'
for index, value in enumerate(Loops):
此行查找所有以數字開頭、中間有“to”并以數字結尾的字串。
m = re.findall(r'\d to \d ', value)
此行將m字串拆分為to.
m = [i.split('to') for i in m]
此行在名為的字典中添加具有起始值的回圈項d
d[f'LoopStart{index 1}'] = int(m[0][0])
此行在名為的字典中添加帶有結束值的回圈項d
d[f'LoopEnd{index 1}'] = int(m[0][-1])
此外,f'{value}'創建字串的程序稱為f-strings.
uj5u.com熱心網友回復:
您可以使用嵌套串列推導:
pl=[f'LoopStart{ln 1} = {ls}, LoopEnd{ln 1} = {le}'
for ln, ls, le in [[int(w) for w in line.split() if w.isnumeric()]
for line in Loops]]
>>> print(', '.join(pl))
LoopStart1 = 0, LoopEnd1 = 965, LoopStart2 = 966, LoopEnd2 = 1969, LoopStart3 = 1970, LoopEnd3 = 2961
打破這一點,這部分制作了找到的數字的子串列:
>>> sl=[[int(w) for w in line.split() if w.isnumeric()]
... for line in Loops]
>>> sl
[[0, 0, 965], [1, 966, 1969], [2, 1970, 2961]]
然后這部分從這些子串列中的值創建一個格式化字串串列:
>>> pl=[f'LoopStart{ln 1} = {ls}, LoopEnd{ln 1} = {le}' for ln, ls, le in sl]
>>> pl
['LoopStart1 = 0, LoopEnd1 = 965', 'LoopStart2 = 966, LoopEnd2 = 1969', 'LoopStart3 = 1970, LoopEnd3 = 2961']
然后一起加入:
>>> ', '.join(pl)
'LoopStart1 = 0, LoopEnd1 = 965, LoopStart2 = 966, LoopEnd2 = 1969, LoopStart3 = 1970, LoopEnd3 = 2961'
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/466037.html
下一篇:插入值串列代替串列中的值
