怎么取出list中值的前5位相同的值
时间: 2023-11-28 18:49:02 浏览: 36
可以使用Python中的Counter函数来实现。Counter函数可以统计一个可迭代对象中每个元素出现的次数,返回一个字典。
例如,对于以下的列表:
```
lst = ['apple', 'banana', 'avocado', 'apricot', 'blueberry', 'cherry', 'coconut', 'date', 'elderberry', 'fig', 'grape', 'guava', 'honeydew', 'kiwi', 'lemon', 'mango', 'nectarine', 'orange', 'papaya', 'peach', 'quince', 'raspberry', 'strawberry', 'tangerine', 'watermelon']
```
我们可以使用Counter函数统计每个元素的出现次数,然后筛选出出现次数最多的5个元素:
```python
from collections import Counter
lst = ['apple', 'banana', 'avocado', 'apricot', 'blueberry', 'cherry', 'coconut', 'date', 'elderberry', 'fig', 'grape', 'guava', 'honeydew', 'kiwi', 'lemon', 'mango', 'nectarine', 'orange', 'papaya', 'peach', 'quince', 'raspberry', 'strawberry', 'tangerine', 'watermelon']
# 统计每个元素出现的次数
counts = Counter([x[:5] for x in lst])
# 取出出现次数最多的5个元素
most_common = counts.most_common(5)
print(most_common)
```
输出结果为:
```
[('apple', 1), ('banan', 1), ('avoca', 1), ('apric', 1), ('blueb', 1)]
```
这里我假设你要取出的是每个元素的前5位相同的值。在统计出现次数时,我取出了每个元素的前5位,使用Counter函数进行统计。最后取出出现次数最多的5个元素,这些元素的前5位相同。