Automate the boring stuff with Python: Comma Code

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

    That one wins for simplicity Hein.

    Only, the author specified:

    "your function should be able to work with any list value passed to it."

    To accompany non strings, add str() tags to al the [i] functions.

    spam = ['apples', 'bananas', 'tofu', 'cats', 'bears', 21]
    def pList(x):
        for i in range(len(x) - 2):
            print(str(x[i]) + ', ', end='')
        print(str(x[-2]) + ' and ' + str(x[-1]))
    pList(spam)
    
    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2021-02-03 16:44
    def commacode(mylist):
        mylist[-1] = 'and ' + mylist[-1]
        mystring = ', '.join(mylist)
        return mystring
    
    spam = ['apple', 'bananas', 'tofu', 'cats']
    
    print commacode(spam)
    
    0 讨论(0)
  • 2021-02-03 16:44

    I'm new to python, there might be other easier solutions but here's mine

        spam = ["cats","dogs","cows","apes"]
        def commaCode(list):
            list[-1] =  "and " + list[-1]
            print(", ".join(list))
    
    
        commaCode(spam)
    
    0 讨论(0)
  • 2021-02-03 16:49
    spam=['apples','bananas','tofu','cats']
    print("'",end="")
    def val(some_parameter):
    
    for i in range(0,len(spam)):
    if i!=(len(spam)-1):
    print(spam[i]+', ',end="")
    else:
    print('and '+spam[-1]+"'")
    val(spam)
    
    0 讨论(0)
  • 2021-02-03 16:50
    def sample(values):
        if len(values) == 0:
             print("Enter some value")
        elif len(values) == 1:
            return values[0]
        else:
            return ', '.join(values[:-1] + ['and ' + values[-1]])
    
    spam = ['apples', 'bananas', 'tofu', 'cats']
    print(sample(spam))
    
    0 讨论(0)
提交回复
热议问题