python映射字符串拆分列表 [英] python map string split list

查看:163
本文介绍了python映射字符串拆分列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将str.split函数映射到字符串数组.即,我想将所有字符串拆分为遵循相同格式的字符串数组.知道如何在python中使用map做到这一点吗?例如,假设我们有一个这样的列表:

I am trying to map the str.split function to an array of string. namely, I would like to split all the strings in a string array that follow the same format. Any idea how to do that with map in python? For example let's assume we have a list like this:

>>> a = ['2011-12-22 46:31:11','2011-12-20 20:19:17', '2011-12-20 01:09:21']

想使用map按空格将字符串拆分(split(")),以使列表为:

want to split the strings by space ( split(" ")) using map to have a list as:

>>> [['2011-12-22', '46:31:11'], ['2011-12-20', '20:19:17'], ['2011-12-20', '01:09:21']]

推荐答案

尽管尚不为人所知,但有一个功能专门为此目的而设计,

Though it isn't well known, there is a function designed just for this purpose, operator.methodcaller:

>>> from operator import methodcaller
>>> a = ['2011-12-22 46:31:11','2011-12-20 20:19:17', '2011-12-20 01:09:21']
>>> map(methodcaller("split", " "), a)
[['2011-12-22', '46:31:11'], ['2011-12-20', '20:19:17'], ['2011-12-20', '01:09:21']]

此技术比使用lambda表达式的等效方法要快.

This technique is faster than equivalent approaches using lambda expressions.

这篇关于python映射字符串拆分列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆