Gla*_*wed 1 python string list
['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']
Run Code Online (Sandbox Code Playgroud)
我想提取与日期对应的分号右边的所有数字.例如,对于日期'2017-07-17',我想返回列表[14,5].到目前为止2017-07-23我只想回来[4].
我怎样才能做到这一点?我只知道迭代索引来提取数字,但这不会得到我对应于某些日期的数字列表.
for eventIndex in range(2,len(path)):
curr_date = path[eventIndex].split(';')[0]
只会得到我遍历的相应数字,但我根本不知道如何获得与每个日期对应的列表.
选择合适的数据结构,例如,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']
Run Code Online (Sandbox Code Playgroud)
在这里,我们迭代列表,对字符串进行分区;,并使用日期部分作为out字典的键,其值是附加的右侧子字符串.
| 归档时间: |
|
| 查看次数: |
46 次 |
| 最近记录: |