Dada una lista de números, escriba un programa en Python para contar números positivos y negativos en una lista.
Ejemplo:
Input: list1 = [2, -7, 5, -64, -14] Output: pos = 2, neg = 3 Input: list2 = [-12, 14, 95, 3] Output: pos = 3, neg = 1
Ejemplo #1: Cuente números positivos y negativos de una lista dada usando el ciclo for
Itere cada elemento de la lista usando for loop y verifique si num >= 0, la condición para verificar números positivos. Si la condición se cumple, aumente pos_count; de lo contrario, aumente neg_count.
# Python program to count positive and negative numbers in a List # list of numbers list1 = [10, -21, 4, -45, 66, -93, 1] pos_count, neg_count = 0, 0 # iterating each number in list for num in list1: # checking condition if num >= 0: pos_count += 1 else: neg_count += 1 print("Positive numbers in the list: ", pos_count) print("Negative numbers in the list: ", neg_count)
Producción:
Positive numbers in the list: 4 Negative numbers in the list: 3
Ejemplo #2: Usando el ciclo while
# Python program to count positive and negative numbers in a List # list of numbers list1 = [-10, -21, -4, -45, -66, 93, 11] pos_count, neg_count = 0, 0 num = 0 # using while loop while(num < len(list1)): # checking condition if list1[num] >= 0: pos_count += 1 else: neg_count += 1 # increment num num += 1 print("Positive numbers in the list: ", pos_count) print("Negative numbers in the list: ", neg_count)
Producción:
Positive numbers in the list: 2 Negative numbers in the list: 5
Ejemplo n.º 3: uso de expresiones lambda de Python
# Python program to count positive # and negative numbers in a List # list of numbers list1 = [10, -21, -4, 45, 66, 93, -11] neg_count = len(list(filter(lambda x: (x < 0), list1))) # we can also do len(list1) - neg_count pos_count = len(list(filter(lambda x: (x >= 0), list1))) print("Positive numbers in the list: ", pos_count) print("Negative numbers in the list: ", neg_count)
Producción:
Positive numbers in the list: 4 Negative numbers in the list: 3
Ejemplo #4: Uso de la comprensión de listas
# Python program to count positive # and negative numbers in a List # list of numbers list1 = [-10, -21, -4, -45, -66, -93, 11] only_pos = [num for num in list1 if num >= 1] pos_count = len(only_pos) print("Positive numbers in the list: ", pos_count) print("Negative numbers in the list: ", len(list1) - pos_count)
Producción:
Positive numbers in the list: 1 Negative numbers in the list: 6