+ 1
List comprehension
Is it possible to do try and except using list comprehension in python? For example : I have list [1,2,3,'h',4], I would like to calculate square of all integers and keep 'h' as it is. [1, 4, 9,'h', 16]
5 ответов
+ 8
I don't think you can use try/except in a list comprehension, but you don't need to because you can get the desired result with if/else:
lst = [1, 2, 3, 'h', 4]
squares = [n**2 if isinstance(n, int) or isinstance(n, float) else n for n in lst]
print(squares) # [1, 4, 9, 'h', 16]
/Edit: This one makes it easier to add more numeric data types:
squares2 = [n**2 if any(isinstance(n, t) for t in (int, float)) else n for n in lst]
print(squares2)
/Edit²: using numbers.Number will detect most numerical types:
from numbers import Number
lst = [1, 2, 3, 4.5, 'h', 6, 7j]
squares3 = [n**2 if isinstance(n, Number) else n for n in lst]
print(squares3) # [1, 4, 9, 20.25, 'h', 36, (-49+0j)]
+ 3
Gordon I'm sure 👌☺️
+ 1
Wow, but can he understand your answer? 😅
+ 1
Thanks Anna ..it was helpful:)
0
If it's only about int or not int, I would use this pattern:
[i**2 if type(i)==int else i for i in l]