【问题标题】:How can I concatenate strings in a tuple if I don't know the length of the tuple?如果我不知道元组的长度,如何连接元组中的字符串?
【发布时间】:2020-12-18 22:30:49
【问题描述】:

考虑这个元组列表:

my_list = [("a", "b"),("a", "b", "c"),("a",)]

理想的结果是:

my_list = ["ab", "abc","a"]

如何用最少的代码实现结果?

我的所有尝试要么导致代码块不流畅,要么完全失败,因为当元组中的字符串数量未知时,我找不到用组合中的字符串替换元组的简单方法。

【问题讨论】:

  • 这能回答你的问题吗? Python convert tuple to string
  • [''.join(t) for t in my_list]
  • 不知道为什么不知道元组中的字符串数量会造成问题。你知道使用len函数可以得到一个元组中的项数吗?

标签: python tuples concatenation


【解决方案1】:

这个怎么样?

my_list = [("a", "b"), ("a", "b", "c"), ("a",)]

my_list = ["".join(x) for x in my_list]

print(my_list)

结果如下:

['ab', 'abc', 'a']

【讨论】:

    【解决方案2】:
    In [131]: my_list = [("a", "b"),("a", "b", "c"),("a",)]                         
    
    In [132]: new_list = ["".join(a) for a in my_list]                              
    
    In [133]: new_list                                                              
    Out[133]: ['ab', 'abc', 'a']
    

    【讨论】:

      【解决方案3】:

      我建议使用str.join,例如:

      new_list = list()        #Initialize output list
      
      for item in my_list:     #Iterate through the original list and store the tuples in "item"
          el = ''.join(item)   #Store the concatenate string in "el"
          new_list.append(el)  #Append "el" to the output list "new_list"
      

      【讨论】:

        【解决方案4】:

        其中一个解决方案是使用两个 for 循环:

        my_list = [("a", "b"), ("a", "b", "c"), ("a",)]
        new_list = []
        for tup in my_list:
            merge = ""
            for item in tup:
                merge += item
            new_list.append(merge)
        print(new_list)
        

        【讨论】:

          猜你喜欢
          • 2022-01-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-05
          相关资源
          最近更新 更多