如何在只对应于特定日期的字符串中返回分号后的数字?

2024-09-30 18:24:15 发布

您现在位置:Python中文网/ 问答频道 /正文

['2017-07-17', '2017-07-27', '2017-07-17;14', '2017-07-17;5', '2017-07-19;11', '2017-07-19;13', '2017-07-23;4', '2017-07-27;-1']

我要提取与日期对应的分号右边的所有数字。例如,对于date'2017-07-17',我想返回列表[14,5]。对于日期2017-07-23,我只想返回[4]。你知道吗

我该怎么做?我只知道通过迭代索引来提取数字,但这不会得到与特定日期对应的数字列表。你知道吗

for eventIndex in range(2,len(path)): curr_date = path[eventIndex].split(';')[0]

只会让我遍历相应的数字,但我只是不知道如何得到对应于每个日期的列表。你知道吗


Tags: pathin列表fordatelenrange数字
2条回答

选择适当的数据结构,例如collections.defaultdict,以list作为工厂:

In [1233]: out = collections.defaultdict(list)

In [1234]: lst = ['2017-07-17', '2017-07-27', '2017-07-17;14', '2017-07-17;5', '2017-07-19;11', '2017-07-19;13', '2017-07-23;4', '2017-07-27;-1']

In [1235]: for i in lst:
      ...:     m, _, n = i.partition(';')
      ...:     if n:
      ...:         out[m].append(n)
      ...:         

In [1236]: out
Out[1236]: 
defaultdict(list,
            {'2017-07-17': ['14', '5'],
             '2017-07-19': ['11', '13'],
             '2017-07-23': ['4'],
             '2017-07-27': ['-1']})

In [1237]: out['2017-07-17']
Out[1237]: ['14', '5']

In [1238]: out['2017-07-23']
Out[1238]: ['4']

在这里,我们遍历列表,对;上的字符串进行分区,并使用日期部分作为out字典的键,其值是附加的右侧子字符串。你知道吗

使用列表中不存在的字符(例如|)连接列表,然后使用正则表达式查找所讨论日期后分号后面的数字:

import re

l = ['2017-07-17', '2017-07-27', '2017-07-17;14', '2017-07-17;5', '2017-07-19;11', '2017-07-19;13', '2017-07-23;4', '2017-07-27;-1']

>>> re.findall('2017-07-17;(\d+)','|'.join(l))
['14', '5']

>>> re.findall('2017-07-23;(\d+)','|'.join(l))
['4']

如果需要它们作为数字数据类型而不是字符串,请使用map(int,...)

>>> list(map(int,re.findall('2017-07-17;(\d+)','|'.join(l))))
[14, 5]

相关问题 更多 >