Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用条纹计数替换字符串_Python_String_List - Fatal编程技术网

Python 用条纹计数替换字符串

Python 用条纹计数替换字符串,python,string,list,Python,String,List,假设我有一个如下形式的字符串: "000000111100011100001011000000001111" 我想创建一个包含1条纹长度的列表: [4, 3, 1, 2, 4] 有一个很好的一行程序吗?如果您不介意itertools import groupby的 >>> s = "000000111100011100001011000000001111" >>> items = set(s) >>> counts = [s.count(

假设我有一个如下形式的字符串:

"000000111100011100001011000000001111"
我想创建一个包含1条纹长度的列表:

[4, 3, 1, 2, 4]

有一个很好的一行程序吗?

如果您不介意itertools import groupby的

>>> s = "000000111100011100001011000000001111"
>>> items = set(s)
>>> counts = [s.count(x) for x in items]
>>> counts
[1, 1]
>>> 
>>> from itertools import groupby
>>> [len(list(g)) for k, g in groupby(s) if k == '1']
[4, 3, 1, 2, 4]

可以使用regex完成,但不如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)]
更加优雅(归功于乔恩):


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

>>> mystr = "000000111100011100001011000000001111"
>>> [len(s) for s in mystr.split('0') if s]
[4, 3, 1, 2, 4]

没有回答这个问题。OP甚至显示了输出应该是什么,这与您所写的完全不匹配..该死,这比我想象的要晚。。。抱歉,这太糟糕了,不过有点可笑:)@RussW If
counts==[1,1]
我猜输入中包含1和0;)为什么不直接使用
1+
?@icktoofay-Ooh,是的,这会让这更美好,只更新一下:
map(len,re.findall('1+',s))
@JonClements-Ooh,好主意。更新,带有一系列优雅
>>> mystr = "000000111100011100001011000000001111"
>>> [len(s) for s in re.split("0+", mystr) if s]
[4, 3, 1, 2, 4]
>>> mystr = "000000111100011100001011000000001111"
>>> [len(s) for s in mystr.split('0') if s]
[4, 3, 1, 2, 4]