从字符串列表中获取整数值

Getting the integer value from a list of strings

我有一个字符串列表,如下所示:

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 循环或字符串切片来做到这一点,但我应该如何/使用哪些命令来专门从这些字符串列表中获取点号(整数)?由于每个数字都有不同的长度。

提前致谢!

您可以使用 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

您可以使用嵌套列表理解:

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'