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

新手上路,请多包涵

目前,我正在阅读这本初学者书籍,并完成了其中一个练习项目“逗号代码”,该项目要求用户构建一个程序,该程序:

将列表值作为参数并返回一个字符串,其中所有项目均以逗号和空格分隔,并插入到最后一项之前。例如,将 以下 垃圾邮件列表传递给该函数将返回“apples、bananas、tofu 和 cats”。但是您的函数应该能够处理传递给它的任何列表值。

 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))

我唯一的问题是,有什么办法可以缩短我的代码吗?还是让它更“pythonic”?

这是我的代码。

 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)

输出:苹果、香蕉、豆腐和猫

原文由 Sutharsan Sethurayar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 576
2 个回答

使用 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'

原文由 Martijn Pieters 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

 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

原文由 Hein de Wilde 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏