python输出列表中负数个数
时间: 2024-03-12 15:43:16 浏览: 61
可以使用以下代码来输出列表中负数的个数:
```python
my_list = [-1, 2, 3, -4, -5, 6, 7, -8]
count = 0
for num in my_list:
if num < 0:
count += 1
print("列表中负数的个数为:", count)
```
输出结果为:
```
列表中负数的个数为: 4
```
在这个例子中,我们首先定义了一个名为 `my_list` 的列表,然后使用一个 `for` 循环遍历列表中的每个元素。如果元素小于0,我们就将 `count` 变量的值加1。最后,我们输出 `count` 变量的值,即列表中负数的个数。
相关问题
python输出列表中负数个数,输入列表
可以通过以下代码实现:
```python
my_list = input("请输入列表,用空格分隔每个元素:").split()
count = 0
for num in my_list:
if int(num) < 0:
count += 1
print("列表中负数的个数为:", count)
```
首先,我们使用 `input()` 函数读取用户输入的字符串,并使用 `split()` 函数将其拆分为一个字符串列表。然后,我们使用一个 `for` 循环来遍历列表中的每个元素,如果元素是负数,就将 `count` 变量加1。最后,我们输出 `count` 变量的值,即列表中负数的个数。
请注意,由于 `input()` 函数返回的是一个字符串,因此我们需要使用 `int()` 函数将字符串转换为整数,以便能够比较列表中的元素是否为负数。
python均值正负数个数统计
可以使用Python的列表推导式和内置函数`sum()`来实现正负数的均值和个数统计。
以下是一个示例代码:
```python
numbers = [1, -2, 3, -4, 5, -6, 7, -8, 9, -10]
# 统计正数的个数和均值
positive_numbers = [x for x in numbers if x > 0]
count_positive = len(positive_numbers)
mean_positive = sum(positive_numbers) / count_positive if count_positive > 0 else 0
# 统计负数的个数和均值
negative_numbers = [x for x in numbers if x < 0]
count_negative = len(negative_numbers)
mean_negative = sum(negative_numbers) / count_negative if count_negative > 0 else 0
print("正数个数:", count_positive)
print("正数均值:", mean_positive)
print("负数个数:", count_negative)
print("负数均值:", mean_negative)
```
输出结果为:
```
正数个数: 5
正数均值: 5.0
负数个数: 5
负数均值: -5.0
```