4

假设我有以下形式的字符串:

"000000111100011100001011000000001111"

我想创建一个包含 1-streaks 长度的列表:

[4, 3, 1, 2, 4]

有没有一个很好的单线?

4

5 回答 5

15

如果你不介意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]
于 2013-07-21T22:54:34.047 回答
2

可以用正则表达式完成,虽然不如 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))
于 2013-07-21T22:56:15.653 回答
1
>>> mystr = "000000111100011100001011000000001111"
>>> [len(s) for s in re.split("0+", mystr) if s]
[4, 3, 1, 2, 4]
于 2013-07-21T23:05:09.877 回答
1

不需要正则表达式,只需str.split

>>> mystr = "000000111100011100001011000000001111"
>>> [len(s) for s in mystr.split('0') if s]
[4, 3, 1, 2, 4]
于 2013-07-21T23:28:46.040 回答
-6
>>> s = "000000111100011100001011000000001111"
>>> items = set(s)
>>> counts = [s.count(x) for x in items]
>>> counts
[1, 1]
>>> 
于 2013-07-21T22:54:11.383 回答