Automate the boring stuff with Python: Comma Code

前端 未结 29 1044
深忆病人
深忆病人 2021-02-03 16:17

Currently working my way through this beginners book and have completed one of the practice projects \'Comma Code\' which asks the user to construct a program which:

29条回答
  •  佛祖请我去吃肉
    2021-02-03 16:34

    def listall(lst):               # everything "returned" is class string
        if not lst:                 # equates to if not True. Empty container is always False
            return 'NONE'           # empty list returns string - NONE
        elif len(lst) < 2:          # single value lists
            return str(lst[0])      # return passed value as a string (do it as the element so 
                                    #  as not to return [])
        return (', '.join(str(i) for i in lst[:-1])) + ' and ' + str(lst[-1])
            # joins all elements in list sent, up to last element, with (comma, space) 
            # AND coverts all elements to string. 
            # Then inserts "and". lastly adds final element of list as a string.
    

    This isn't designed to answer the original question. It's to show how to define the function addressing all the matters requested by the book without being complex. I think that's acceptable as the original question posts the books "Comma Code" test. Important Note: Something I found confusing that might help others is. "a list value" means a value of type list or "an entire list" it doesn't mean an individual value (or slices) from "type list". Hope that's helpful

    Here are the samples I used to test it:

    empty = []
    ugh = listall(empty)
    print(type(ugh))
    print(ugh)
    test = ['rabbits', 'dogs', 3, 'squirrels', 'numbers', 3]
    ughtest = listall(test)
    print(type(ughtest))
    print(ughtest)
    supertest = [['ra', 'zues', 'ares'],
                ['rabbit'],
                ['Who said', 'biscuits', 3, 'or', 16.71]]
    one = listall(supertest[0])
    print(type(one))
    print(one)
    two = listall(supertest[1])
    print(type(two))
    print(two)
    last = listall(supertest[2])
    print(type(last))
    print(last)
    
    

提交回复
热议问题