python统计人数代码
时间: 2023-07-09 20:43:25 浏览: 60
以下是一个简单的Python代码,可以用来统计列表中某个元素出现的次数,从而实现统计人数的功能:
```python
names = ['Alice', 'Bob', 'Charlie', 'Alice', 'David', 'Charlie', 'Alice']
count = 0
for name in names:
if name == 'Alice':
count += 1
print("There are", count, "people named Alice.")
```
输出结果为:
```
There are 3 people named Alice.
```
注意,这个代码只能统计特定元素出现的次数,如果你需要统计不同元素的出现次数,可以使用Python的字典数据结构。例如:
```python
names = ['Alice', 'Bob', 'Charlie', 'Alice', 'David', 'Charlie', 'Alice']
counts = {}
for name in names:
if name in counts:
counts[name] += 1
else:
counts[name] = 1
for name, count in counts.items():
print("There are", count, "people named", name)
```
输出结果为:
```
There are 3 people named Alice
There are 1 people named Bob
There are 2 people named Charlie
There are 1 people named David
```