Uses of Python's “from” keyword?

前端 未结 6 636
一整个雨季
一整个雨季 2021-01-11 11:53

Are there any other uses for Python\'s \"from\" keyword aside from import statements?

6条回答
  •  攒了一身酷
    2021-01-11 12:43

    Since there are a lot of updates to python from the time of posting the question, here is a new use case of from keyword in python3 will show you the use with an example

    def flatten(l):
        for element in l:
            if type(element) == type(list()):
                yield from flatten(element)
            else:
                yield element
    
    def flatten2(l):
        for element in l:
            if type(element) == type(list()):
                yield flatten2(element)
            else:
                yield element
    
    
    unflatted_list = [1,2,3,4,[5,6,[7,8],9],10]
    flatted_list = list(flatten(unflatted_list))
    flatted_list2 = list(flatten2(unflatted_list))
    print(flatted_list) # [1,2,3,4,5,6,7,8,9,10]
    print(flatted_list2) # [1, 2, 3, 4, , 10]
    

提交回复
热议问题