Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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_List - Fatal编程技术网

Python 计算列表中相同长度的项目

Python 计算列表中相同长度的项目,python,list,Python,List,我正在尝试使用Python风格的编码移植cgi脚本 sequence = "aaaabbababbbbabbabb" res = sequence.split("a") + sequence.split("b") res = [l for l in res if l] 结果是 >>> res ['bb', 'b', 'bbbb', 'bb', 'bb', 'aaaa', 'a', 'a', 'a', 'a'] 这是~100loc in C。现在我想有效地计算res列表中具有

我正在尝试使用Python风格的编码移植cgi脚本

sequence = "aaaabbababbbbabbabb"
res = sequence.split("a") + sequence.split("b")
res = [l for l in res if l]
结果是

>>> res
['bb', 'b', 'bbbb', 'bb', 'bb', 'aaaa', 'a', 'a', 'a', 'a']
这是~100loc in C。现在我想有效地计算res列表中具有相同长度的项目。例如,这里res包含5个长度为1的元素、3个长度为2的元素和2个长度为4的元素


问题是序列字符串可能非常大。

给定字符串列表生成字符串长度直方图的最简单方法是使用
集合。计数器

>>> from collections import Counter
>>> a = ["a", "b", "aaa", "bb", "aa", "bbb", "", "a", "b"]
>>> Counter(map(len, a))
Counter({1: 4, 2: 2, 3: 2, 0: 1})
编辑:还有一种更好的方法可以找到相等字符的运行,即
itertools.groupby()


你可能会做类似的事情

occurrences_by_length={} # map of length of string->number of strings with that length.
for i in (len(x) for x in (sequence.split("a")+sequence.split("b"))):
    if i in occurrences_by_length:
        occurrences_by_length[i]=occurrences_by_length[i]+1
    else:
        occurrences_by_length[i]=1

现在,每个字符串的长度映射到该长度的字符串出现的次数。

您能解释一下代码的作用吗?我不确定你想用它完成什么。你应该记下你想要的输出,例如,带有数字键和值的字典。@Blender我的代码查找具有相同字符的子序列。我想问的是一种计算列表中长度x序列存在多少次的方法。我不会回答你的评论。我只接受这个anwser作为一个解决方案。我通常会发现
for I in(我的列表中的某物(x)for x)
很难阅读。对于我的列表中的x,您可以将其转换为
:i=something(x)
occurrences_by_length={} # map of length of string->number of strings with that length.
for i in (len(x) for x in (sequence.split("a")+sequence.split("b"))):
    if i in occurrences_by_length:
        occurrences_by_length[i]=occurrences_by_length[i]+1
    else:
        occurrences_by_length[i]=1