如果我不知道元组的长度,如何在元组中连接字符串?



考虑以下元组列表:

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

理想的结果是:

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

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

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

这个怎么样?

my_list = [("a", "b"), ("a", "b", "c"), ("a",)]
my_list = ["".join(x) for x in my_list]
print(my_list)

结果如下:

['ab', 'abc', 'a']
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']

我建议使用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"

解决方案之一是使用两个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)

最新更新