Chi*_*nke 5 python split join list
有没有任何标准的python库可以让你做这样的事情?
>>> [1,0,2,3,0,5,6].split([0])
>>> [[1],[2,3],[5,6]]
>>> [[1],[2,3],[5,6]].join([0])
>>> [1,0,2,3,0,5,6]
Run Code Online (Sandbox Code Playgroud)
对我来说,感觉就像一个非常基本的东西,经常需要.请注意,字符串默认支持这些方法.
不确定是否有任何内置函数可以轻松完成此操作,但您可以使用 itertools:
>>> from itertools import groupby, chain, islice, cycle
>>> lis = [1,0,2,3,0,5,6]
>>> [list(g) for k, g in groupby(lis, key =lambda x: x==0) if not k]
[[1], [2, 3], [5, 6]]
>>> lis1 = [[1],[2,3],[5,6]]
>>> c = [[0]]*(len(lis1) - 1)
>>> list(chain.from_iterable(roundrobin(lis1, c)))
[1, 0, 2, 3, 0, 5, 6]
Run Code Online (Sandbox Code Playgroud)
Roundrobin第二个中使用的食谱:
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
pending = len(iterables)
nexts = cycle(iter(it).next for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))
Run Code Online (Sandbox Code Playgroud)