按字符串拆分列表和字符串列表

时间:2013-04-19 17:28:23

标签: python list split

是否有一种方便的pythonic方法来按搜索字符串拆分列表(即使列表包含非字符串并具有嵌套列表)。例如,假设我想将以下内容拆分为',':

[[ 'something', ',', 'eh' ], ',', ['more'], ',', 'yet more', '|', 'even more' ]

这将成为:

[[[ 'something', ',', 'eh' ]], [['more']], ['yet more', '|', 'even more']]

2 个答案:

答案 0 :(得分:7)

看看itertools.groupby

In [1]: from itertools import groupby

In [2]: lst = [[ 'something', ',', 'eh' ], ',', ['more'], ',', 'yet more', '|', 'even more' ]

In [3]: [list(group) for key, group in groupby(lst, lambda x: x!=',') if key]
Out[3]: [[['something', ',', 'eh']], [['more']], ['yet more', '|', 'even more']]

它基本上会根据条件(item != ',')将列表中的项目拆分为组,而理解检查if k会筛选出False的组 - 这些项目是等于','

In [4]: for key, group in groupby(lst, lambda x: x!=','):
   ...:     print key, list(group)
   ...:     
True [['something', ',', 'eh']]
False [',']
True [['more']]
False [',']
True ['yet more', '|', 'even more']

答案 1 :(得分:0)

派对迟到但是FWIW,我认为itertools.takewhileiter的组合带有哨兵值可以提供快速解决方案

from itertools import takewhile

z = [[ 'something', ',', 'eh' ], ',', ['more'], ',',
  'yet more', '|', 'even more' ]
z = iter(z)
def provider():
  return list(takewhile(lambda x: x != ',', z))

for i in iter(provider, []):
  print i

... 
[['something', ',', 'eh']]
[['more']]
['yet more', '|', 'even more']