Automate the boring stuff with Python: Comma Code

前端 未结 29 951
深忆病人
深忆病人 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:44

    Here's a solution that handles the Oxford comma properly. It also copes with an empty list, in which case it returns an empty string.

    def list_thing(seq):
        return (' and '.join(seq) if len(seq) <= 2
            else '{}, and {}'.format(', '.join(seq[:-1]), seq[-1]))
    
    spam = ['apples', 'bananas', 'tofu', 'cats']
    
    for i in range(1 + len(spam)):
        seq = spam[:i]
        s = list_thing(seq)
        print(i, seq, repr(s))
    

    output

    0 [] ''
    1 ['apples'] 'apples'
    2 ['apples', 'bananas'] 'apples and bananas'
    3 ['apples', 'bananas', 'tofu'] 'apples, bananas, and tofu'
    4 ['apples', 'bananas', 'tofu', 'cats'] 'apples, bananas, tofu, and cats'
    

    FWIW, here's a slightly more readable version using an if-else statement instead of a conditional expression:

    def list_thing(seq):
        if len(seq) <= 2:
            return ' and '.join(seq)
        else:
            return '{}, and {}'.format(', '.join(seq[:-1]), seq[-1])    
    

    And here's a slightly less readable version, using an f-string:

    def list_thing(seq):
        if len(seq) <= 2:
            return ' and '.join(seq)
        else:
            return f"{', '.join(seq[:-1])}, and {seq[-1]}"   
    

    Note that Martijn's code produces 'apples, and bananas' from the 2 item list. My answer is more grammatically correct (in English), however Martijn's is more technically correct because it does exactly what's specified in the OP's quote (although I disagree with his handling of the empty list).

提交回复
热议问题