Python列出出现的最少名字(多个出现频率为1)
时间: 2023-05-31 14:01:59 浏览: 43
假设我们有一个名字列表names:
```python
names = ['John', 'Mary', 'John', 'Michael', 'Sarah', 'Mary', 'John', 'Sarah']
```
我们可以使用Python的collections模块中的Counter类来计算每个名字出现的次数。
```python
from collections import Counter
names = ['John', 'Mary', 'John', 'Michael', 'Sarah', 'Mary', 'John', 'Sarah']
name_count = Counter(names)
print(name_count)
```
输出:
```
Counter({'John': 3, 'Mary': 2, 'Sarah': 2, 'Michael': 1})
```
现在我们可以使用Counter的most_common()方法来获取出现次数最少的名字。
```python
least_common_names = [name for name, count in name_count.items() if count == name_count.most_common()[-1][1]]
print(least_common_names)
```
输出:
```
['Michael']
```
如果有多个出现次数为1的名字,则它们都将被列出。
相关问题
Python计算出现频率最多和最少的名字
假设有一个名字列表names,可以使用Python的collections模块中的Counter类来计算每个名字出现的频率,然后找出出现频率最高和最低的名字。
代码如下:
```python
from collections import Counter
names = ['Alice', 'Bob', 'Charlie', 'Alice', 'David', 'Charlie', 'Alice']
name_freq = Counter(names)
most_common_name = name_freq.most_common(1)[0][0]
least_common_name = name_freq.most_common()[-1][0]
print("Most common name:", most_common_name)
print("Least common name:", least_common_name)
```
运行结果:
```
Most common name: Alice
Least common name: David
```
解释:
- 首先使用Counter类计算每个名字出现的频率,这里将名字列表names作为Counter类的参数传入,得到一个名字出现频率的字典name_freq。
- 然后使用most_common()方法找出出现频率最高的名字,这里取第一个元素的第一个元素,即most_common(1)[0][0]。
- 同样使用most_common()方法找出出现频率最低的名字,这里取最后一个元素的第一个元素,即most_common()[-1][0]。
python随机生成50个1到20,统计整数出现频率
好的,我可以帮你解决这个问题。下面是代码示例:
```python
import random
# 生成50个1到20的随机整数
numbers = [random.randint(1, 20) for _ in range(50)]
# 统计整数出现频率
frequency = {}
for num in numbers:
if num in frequency:
frequency[num] += 1
else:
frequency[num] = 1
# 输出结果
for num, freq in frequency.items():
print(f"{num}出现了{freq}次")
```
这段代码首先使用 random 模块生成了 50 个 1 到 20 的随机整数,然后使用字典统计每个整数出现的次数,最后输出结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)