Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

python - Unable to convert output to list

How to create a function that takes a list of non-negative integers and strings and return a new list without the strings?

Eg. filter_list([1, 2, "a", "b"]) ? [1, 2]

Issue: Not able to convert output to list

def filter_list(a):
    mylist=[]
    if type(a)==list:
        for i in a:
            if type(i)==int:
                output=print(i)
        mylist+=output
        return mylist

What am I doing wrong?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The mistake you made is that you are assigning the value returned by print() to output (which is None) and then you are adding a None type object to a list object which is an invalid operation. You can fix your code by doing something like this :

def filter_list(a):
    mylist=[]
    if type(a)==list:
        for i in a:
            if type(i)==int:
                print(i)
                mylist+=[i]
        return mylist

However this can be done in a much prettier way using List comprehensions!
List comprehension is a way to create a new list using a relatively much shorter syntax.

[elem for elem in _list if type(elem) is int]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...