How to extract numbers from a list in Python?
To extract numbers from a list, you can use a loop to iterate through each element of the list and extract numbers by checking the type of each element.
Here is an example code:
def extract_numbers(lst):
numbers = []
for item in lst:
if isinstance(item, (int, float)):
numbers.append(item)
return numbers
# 测试示例
my_list = [1, 2, 'a', 3.14, 'b', 4]
result = extract_numbers(my_list)
print(result)
The output is: [1, 2, 3.14, 4]
In the above example, the function extract_numbers takes a list as a parameter. It iterates through each element in the list using a loop and uses the isinstance function to determine if the element is of type integer or float. If it is a numeric type, it adds it to the numbers list. Finally, the function returns the numbers list.