【问题标题】:Replace dashes with whitespaces for all elements across a tuple?用空格替换元组中所有元素的破折号?
【发布时间】:2022-07-06 23:04:09
【问题描述】:

我正在构建这两个问题,因为它们并没有完全回答我的问题: How to change values in a tuple? Python: Replace "-" with whitespace

如果我有这样的元组:

tuple = [('Hi', 'Hello-World', 'Earth), ('Hello-World', 'Hi), ...]

如何用空格替换元组中所有列表中所有元素的破折号?上一个 Stack Overflow 问题涉及更改元组中一个列表的特定索引,但如果一个元素多次出现需要替换,则不会。

我已尝试执行以下操作,但效果不佳:

tuple_new = [x.replace('-', ' ') for x in tuple]

但如果我为元组中的特定列表执行此操作,则它适用于该元组列表。我试图避免必须做单独的列表,而是尝试一次做所有的事情。

tuple_new = [x.replace('-', ' ') for x in tuple[0]]

我知道元组是不可变的,这就是我无法弄清楚这一点的原因。这可能吗?非常感谢任何帮助 - 谢谢。

【问题讨论】:

    标签: python tuples


    【解决方案1】:

    正确表达:

    a = [('Hi', 'Hello-World', 'Earth'), ('Hello-World', 'Hi')]
    newa = [tuple([x.replace('-', ' ') for x in tup]) for tup in a]
    
    >>> newa
    [('Hi', 'Hello World', 'Earth'), ('Hello World', 'Hi')]
    

    【讨论】:

      【解决方案2】:

      首先,不要将任何变量命名为 tuple,它是一个内置函数,当您命名变量 tuple 时,您会错过 method

      def changer(data):
          if type(data) == str:
              return data.replace("-", " ")
          elif type(data) == list:
              return [changer(x) for x in data]
          elif type(data) == tuple:
              return [changer(x) for x in data]
      tpl = [('Hi', 'Hello-World', 'Earth'), ('Hello-World', 'Hi')]
      
      changer(tpl)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-01-14
        • 1970-01-01
        • 2012-04-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-11
        相关资源
        最近更新 更多