Python Code: Generate and Filter Odd Numbers from a Random List
import random
# Generate a list of 10 random numbers from 1 to 10 (inclusive)
num_list = [random.randint(1, 10) for i in range(10)]
# Filter out even numbers using list comprehension
odd_list = [num for num in num_list if num % 2 != 0]
# Print the original list and the odd numbers list
print('Original list:', num_list)
print('Odd numbers list:', odd_list)
This code generates a list of 10 random numbers from 1 to 10 (inclusive) and then uses list comprehension to filter out even numbers, leaving only odd numbers in a new list. The original list and the odd numbers list are then printed for verification.
原文地址: https://www.cveoy.top/t/topic/n5sq 著作权归作者所有。请勿转载和采集!