[英]How can I check the length of consecutive characters in a list in python?
Basically say I have a list in python基本上说我在 python 中有一个列表
lst = [6, 6, 7, 1, 1, 1, 1, 4, 1]
the program should return 4 because the number '1' is displayed 4 times in a consecutive manner.程序应返回 4,因为数字“1”以连续方式显示 4 次。 Btw the number 6 also displays in a consecutive manner but the program should get the number that shows up the most while being consecutive
顺便说一句,数字 6 也以连续方式显示,但程序应该获得在连续时出现最多的数字
more examples:更多示例:
[6, 4, 4, 4, 1, 1, 7]
should output 3 because '4' is consecutive 3 times应该 output 3 因为“4”是连续的 3 次
I've been stuck on this problem for a while now, any advice??我已经被这个问题困扰了一段时间了,有什么建议吗?
groupby()
will give you individual groups of the same value by default: groupby()
默认情况下将为您提供相同值的各个组:
> [list(g) for k, g in groupby(lst)]
[[6, 6], [7], [1, 1, 1, 1], [4], [1]]
You can pass that to max()
with a key of len
to get the longest one:您可以使用
len
键将其传递给max()
以获得最长的:
> from itertools import group-by
> lst = [6, 6, 7, 1, 1, 1, 1, 4, 1]
> max((list(g) for k, g in groupby(lst)), key=len)
[1, 1, 1, 1]
That's the longest grouping, from which you can get the length.这是最长的分组,您可以从中获得长度。 Alternatively you can just build a list of lengths and call
max
without the key:或者,您可以只构建一个长度列表并在没有密钥的情况下调用
max
:
max(len(list(g)) for k, g in groupby(lst))
You could use list.count()
along with set(list)
to extract unique values and then enlist the count for each unique value.您可以使用
list.count()
和set(list)
来提取唯一值,然后为每个唯一值登记计数。
lst = [6, 6, 7, 1, 1, 1, 1, 4, 1]
unique = set(lst)
count = [lst.count(k) for k in unique]
print(' unique: {} \n count: {} \n'.format(unique, count))
Output : Output :
unique: {1, 4, 6, 7}
count: [5, 1, 2, 1]
Use numpy.unique
to get both the unique values and their respective counts.使用
numpy.unique
获取唯一值及其各自的计数。
import numpy as np
unique, count = np.unique(lst, return_counts=True)
print(' unique: {} \n count: {} \n'.format(unique, count))
Output : Output :
unique: [1 4 6 7]
count: [5 1 2 1]
Use Counter
from Colections
.使用
Colections
中的Counter
。 This returns a dictionary with the unique values as the keys and the values as their respective counts.这将返回一个字典,其中唯一值作为键,值作为它们各自的计数。
from collections import Counter
Counter(lst)
Output : Output :
Counter({6: 2, 7: 1, 1: 5, 4: 1})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.