can anyone solve this by using list comprehension method like fizzBuzz problem

75 views Asked by At
l=["Sai", "prasad", 1234,12.34, [1,2,3,4]]
def filter_int(l):
    l1=[]
    for i in l:
        if type(i)==int or type(i)==float:
            l1.append(i)
        elif type(i)==list:
            for j in i:
                l1.append(j)
    return l1
                
   
filter_int(l)

# i tried this 
l=["Sai", "prasad", 1234,12.34, [1,2,3,4]]
def filter_int(l):
    l1=[]
    [l1.append(i) if type(i)==int or type(i)==float else l1.append(i) if type(i)==list else i for i in l]
    return l1
filter_int(l)

my existing output is

[1234, 12.34, [1, 2, 3, 4]]

my expected output is

[1234, 12.34, 1, 2, 3, 4]

(..i want this output from above list comprehension)

4

There are 4 answers

0
Shorn On

In your line of

[l1.append(i) if type(i)==int or type(i)==float else l1.append(i) if type(i)==list else i for i in l]

you called l1.append(i) if type(i) == list. This makes it so you are appending the list as is. Simply change it to extend(i).

[l1.append(i) if type(i)==int or type(i)==float else l1.extend(i) if type(i)==list else i for i in l]

#output
[1234, 12.34, 1, 2, 3, 4]

As pointed out by @PranavHosangadi and @CrazyChucky, you shouldn't be using list comprehensions for this but rather use a loop. However, under the constraint of needing to use a list comprehension in this fashion, this should fix your issue.

0
Ido On

You can use list.extend

def filter_int(l):
    l1=[]
    [l1.append(i) if type(i)==int or type(i)==float else l1.extend(i) if type(i)==list else i for i in l]
    return l1

If the depth of the list is unknown you can use a recursive solution like so

def filter_int(l):
    l1=[]
    [l1.append(i) if type(i)==int or type(i)==float else l1.extend(filter_int(i)) if type(i)==list else i for i in l]
    return l1
0
Copperfield On

you can first force every element in your initial data to be a list (assuming only one level of nesting) and then use itertools.chain.from_iterable to flatten it, and then filter it out

>>> data=["Sai", "prasad", 1234,12.34, [1,2,3,4]]
>>> import itertools
>>> [x for x in itertools.chain.from_iterable(y if isinstance(y,list) else [y] for y in data) if isinstance(x,(int,float))]
[1234, 12.34, 1, 2, 3, 4]

or if import aren't allow:

>>> [x for sublist in [y if isinstance(y,list) else [y] for y in data] for x in sublist if isinstance(x,(int,float))]
[1234, 12.34, 1, 2, 3, 4]

here [y if isinstance(y,list) else [y] for y in data] do the same as above, force everything to be a list, then flatten it with a nested for in the comprehension and filter it out

0
Kelly Bundy On

Another, using a dict (less efficient but kinda neat):

def filter_int(l):
    return [
        j
        for i in l
        for j in {
            int: [i],
            float: [i],
            list: i
        }.get(type(i), ())
    ]