Home > Back-end >  How do sort the elements by type(int, float, str) that fall from the input list to the output list?
How do sort the elements by type(int, float, str) that fall from the input list to the output list?

Time:11-16

There is a list from the user:

user_list = [1, 3.5, "xx", "gg", 6, "2"].
new_list = []

How to make it so that with the help of "list comprehension" from user_list to new_list moved:

  1. Value with type (float)
  2. Even number with type(int)
  3. All elements that have type (str) turned into -2 and were sent to a new_list

CodePudding user response:

not a good way to achive result but, using list comprehension

>>> user_list = [1, 3.5, "xx", "gg", 6, "2"]                  
>>> new_list = [*[i for i in user_list if type(i)==float], *[i for i in user_list if type(i)==int], *[-2 for i in user_list if type(i)==str]]
>>> new_list
[3.5, 1, 6, -2, -2, -2]

CodePudding user response:

Using one list comprehension, this should give you new_list :

new_list = [(lambda x : -2 if type(x)==str else x)(x) for x in user_list if ((type(x)==float) or (type(x)==int and x%2==0) or (type(x)==str))]

As others have mentioned, a list comprehension is probably not the standard way to compute this result.

  • Related