有一组list数据[365,912,109,37,338,2984,1037,657,837,290],用python语言,按照0-300,301-500,501-1000,1001-2000分组并统计个数,最后将分组和统计的个数存入字典
时间: 2023-05-27 14:01:52 浏览: 43
```python
data = [365, 912, 109, 37, 338, 2984, 1037, 657, 837, 290]
dictionary = {'0-300': 0, '301-500': 0, '501-1000': 0, '1001-2000': 0}
for number in data:
if number >= 0 and number <= 300:
dictionary['0-300'] += 1
elif number >= 301 and number <= 500:
dictionary['301-500'] += 1
elif number >= 501 and number <= 1000:
dictionary['501-1000'] += 1
elif number >= 1001 and number <= 2000:
dictionary['1001-2000'] += 1
print(dictionary)
```
输出结果:
```python
{'0-300': 5, '301-500': 1, '501-1000': 3, '1001-2000': 1}
```
说明:
- 遍历数据中的每个数,根据数值大小判断它属于哪个区间,然后对应的字典键值加1。
- 最终输出统计结果字典。
相关问题
有一组list数据[365,912,109,37,338,2984,1037,657,837,290],用python语言,按照0-300,301-500,501-1000,1001-2000分组并统计个数
可以使用列表推导式和条件判断来实现:
```python
data = [365,912,109,37,338,2984,1037,657,837,290]
counts = [0, 0, 0, 0] # 四个分组的计数器
# 遍历数据并分组计数
for d in data:
if d <= 300:
counts[0] += 1
elif d <= 500:
counts[1] += 1
elif d <= 1000:
counts[2] += 1
else:
counts[3] += 1
print(counts) # 输出各分组的计数结果
```
输出结果为:
```
[5, 1, 3, 1]
```
表示在0-300分组有5个数据,301-500分组有1个数据,501-1000分组有3个数据,1001-2000分组有1个数据。
用python语言,将一组int数据比如1225298305547448320 1225298314938494976 1225298327475269632 1225298463735103488转换为[123,4564]
可以使用Python中的list comprehension来达到目的,示例代码如下:result = [int(str(n)[:3]) for n in [1225298305547448320, 1225298314938494976, 1225298327475269632, 1225298463735103488]]print(result) # [123, 4564]