'Identify numbers in a list comprehension [duplicate]
I want to use a list comprehension to create a list containing the numbers greater than 5 from the following text: "I have bought 10 cameras of which only 7 are working, while the other three are broken". I have been able to write a script to know if there are numbers in that sentence, but I am not able to extract them in a new list.
str1 = ('I have bought 10 cameras of which only 7 are working, while the other three are broken')
print(any(map(str.isdigit,
Solution 1:[1]
This would work:
str1 = ('I have bought 10 cameras of which only 7 are working, while the other 3 are broken')
num_greater_than_5 = [int(num) for num in str1.split() if num.isnumeric() and int(num) > 5]
print(num_greater_than_5) // Output: [10, 7]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aravind G. |
