假设我有以下形式的字符串:
"000000111100011100001011000000001111"
我想创建一个包含 1-streaks 长度的列表:
[4, 3, 1, 2, 4]
有没有一个很好的单线?
如果你不介意from itertools import groupby
...
>>> from itertools import groupby
>>> [len(list(g)) for k, g in groupby(s) if k == '1']
[4, 3, 1, 2, 4]
可以用正则表达式完成,虽然不如 itertools 解决方案那么优雅
answer = [len(item) for item in filter(None, re.split(r"[^1]+", test_string))]
或者,更优雅:
answer = [len(item) for item in re.findall(r"1+", test_string)]
更优雅(感谢 Jon):
answer = map(len, re.findall("1+", test_string))
>>> mystr = "000000111100011100001011000000001111"
>>> [len(s) for s in re.split("0+", mystr) if s]
[4, 3, 1, 2, 4]
不需要正则表达式,只需str.split
>>> mystr = "000000111100011100001011000000001111"
>>> [len(s) for s in mystr.split('0') if s]
[4, 3, 1, 2, 4]
>>> s = "000000111100011100001011000000001111"
>>> items = set(s)
>>> counts = [s.count(x) for x in items]
>>> counts
[1, 1]
>>>