简体   繁体   English

如何检查 python 列表中连续字符的长度?

[英]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))

Two different questions may help.两个不同的问题可能会有所帮助。

First to transform the text into list you can check this answer.首先将文本转换为列表,您可以检查答案。

Once you have your list, you need to count consecutive values, it was asked and solved here .一旦你有了你的列表,你需要计算连续的值,这里被问到并解决

Solution解决方案

Method-1方法一

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] 

Method-2方法二

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] 

Method-3方法三

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM