【问题标题】:How to remove unwanted commas from a python list [duplicate]如何从python列表中删除不需要的逗号[重复]
【发布时间】:2017-01-05 23:06:38
【问题描述】:

我正在为初学者的 Python 书做一个练习。我坚持的项目如下:“编写一个函数,将值列表作为参数并返回一个字符串,其中所有项目用逗号和空格分隔。您的函数应该能够与任何列表一起使用传递给它的值”

这是我的代码:

def passInList(spam):
       for x in range(len(spam)):
           z = spam[x] + ', ' 
           print(z,end= ' ')

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

预期输出是 - '苹果、香蕉、豆腐和猫'。

我的输出是-'苹果、香蕉、豆腐和猫,'

我遇到的问题是,我似乎无法摆脱“猫”末尾的逗号。

感谢您的建议。

【问题讨论】:

  • 与您的问题没有直接关系,但是:作业说您应该返回一个字符串,但您的函数不返回任何内容。

标签: python


【解决方案1】:

您可以减少代码以使用join,在其中给它提供分隔符以及要连接在一起的列表。

def passInList(spam):
       print(', '.join(spam))

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

【讨论】:

  • 谢谢。 (加入工作)
【解决方案2】:

正如人们在这里发布的那样,join 已经存在。但如果练习是为了了解如何实现join,那么这里有一种可能性:

def passInList(spam):
    s = spam[0]
    for word in spam[1:]:
        s += ', ' + word
    return s

也就是说,你取第一个单词,然后用逗号连接接下来的每个单词。

实现这一点的另一种选择是使用函数式编程,即在这种情况下,reduce 函数:

def passInList(spam):
    return functools.reduce(lambda x, y: x + ', ' + y, spam)

每当使用聚合方案时,例如在以前的实现中使用 s += ...,就会想到 reduce

【讨论】:

    【解决方案3】:

    使用join方法:

    spam=['apples', 'bananas', 'tofu', 'and cats']
    print(', '.join(spam))
    

    【讨论】:

      【解决方案4】:

      添加 if 语句以仅在 x 小于 len(spam) -1 时添加逗号, 或者更好的是,使用 str 类的连接函数

      【讨论】:

        【解决方案5】:

        您可以使用join 函数,该函数以'str'.join(list) 语法调用。它将列表中的所有元素与str 连接起来

        >>> spam=['apples', 'bananas', 'tofu', 'and cats']
        >>> my_string = ', '.join(spam)
        >>> my_string
        'apples, bananas, tofu, and cats'
        

        【讨论】:

          猜你喜欢
          • 2016-04-29
          • 2022-01-23
          • 2016-03-07
          • 2020-10-20
          • 2023-01-26
          • 1970-01-01
          • 2015-04-17
          相关资源
          最近更新 更多