用Python自动化无聊的事情:Comma Cod

2024-05-27 11:18:04 发布

您现在位置:Python中文网/ 问答频道 /正文

目前我正在学习这本初学者手册,并且已经完成了一个实践项目“逗号代码”,它要求用户构建一个程序,该程序:

takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the below spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it.

spam = ['apples', 'bananas', 'tofu', 'cats']

我对这个问题的解决方案(效果非常好):

spam= ['apples', 'bananas', 'tofu', 'cats']
def list_thing(list):
    new_string = ''
    for i in list:
        new_string = new_string + str(i)
        if list.index(i) == (len(list)-2):
            new_string = new_string + ', and '
        elif list.index(i) == (len(list)-1):
            new_string = new_string
        else:
            new_string = new_string + ', '
    return new_string

print (list_thing(spam))

我唯一的问题是,有没有办法缩短代码?或者让它更像是“Python”?

这是我的密码。

def listTostring(someList):
    a = ''
    for i in range(len(someList)-1):
        a += str(someList[i])
    a += str('and ' + someList[len(someList)-1])
    print (a)

spam = ['apples', 'bananas', 'tofu', 'cats']
listTostring(spam)

产量:苹果、香蕉、豆腐和猫


Tags: andthetonewstringlenwithspam
3条回答

我试过了,希望这就是你想要的:

spam= ['apples', 'bananas', 'tofu', 'cats']

def list_thing(list):

#creating a string then splitting it as list with two items, second being last word
    new_string=', '.join(list).rsplit(',', 1)    

#Using the same method used above to recreate string by replacing the separator.

    new_string=' and'.join(new_string)
    return new_string

print(list_thing(spam))

使用str.join()用分隔符连接字符串序列。如果对除最后一个单词之外的所有单词都这样做,则可以在此处插入' and '

def list_thing(words):
    if len(words) == 1:
        return words[0]
    return '{}, and {}'.format(', '.join(words[:-1]), words[-1])

打破这个:

  • words[-1]获取列表的最后一个元素。words[:-1]对列表进行切片,以生成一个新列表,其中除最后一个单词外,所有单词均为

  • ', '.join()生成一个新字符串,将str.join()的所有参数字符串与', '连接。如果输入列表中只有一个元素,则返回该元素,不连接。

  • '{}, and {}'.format()将逗号连接的单词和最后一个单词插入模板(用牛津逗号完成)。

如果传入一个空列表,上面的函数将引发一个IndexError异常;如果您认为空列表是该函数的有效用例,则可以在函数中专门测试该情况。

所以上面用', '将除最后一个之外的所有单词连接起来,然后用' and '将最后一个单词添加到结果中。

请注意,如果只有一个单词,则得到该单词;在这种情况下没有可连接的词。如果有两个,则得到'word1 and word 2'。更多的单词产生'word1, word2, ... and lastword'

演示:

>>> def list_thing(words):
...     if len(words) == 1:
...         return words[0]
...     return '{}, and {}'.format(', '.join(words[:-1]), words[-1])
...
>>> spam = ['apples', 'bananas', 'tofu', 'cats']
>>> list_thing(spam[:1])
'apples'
>>> list_thing(spam[:2])
'apples, and bananas'
>>> list_thing(spam[:3])
'apples, bananas, and tofu'
>>> list_thing(spam)
'apples, bananas, tofu, and cats'

我用了不同的方法。我是个初学者,所以我不知道这是不是最干净的方法。对我来说,这似乎是最简单的方式:

spam = ['apples', 'pizza', 'dogs', 'cats']

def comma(items):
    for i in range(len(items) -2):
        print(items[i], end=", ")# minor adjustment from one beginner to another: to make it cleaner, simply move the ', ' to equal 'end'. the print statement should finish like this --> end=', '
    print(items[-2] + 'and ' + items[-1]) 

comma(spam)

它将给出输出:

apples, pizza, dogs and cats

相关问题 更多 >

    热门问题