将 Python 元组列表转换为字符串列表


使用 Python 处理数据时,我们可能会遇到元素为元组的列表。然后我们需要进一步将元组转换为字符串列表。

使用 join

join() 返回一个字符串,其中序列中的元素已由 str 分隔符连接。我们将向此函数提供列表元素作为参数,并将结果放入列表中。

示例

 立即演示

listA = [('M','o','n'), ('d','a','y'), ('7', 'pm')]
# Given list
print("Given list : \n", listA)
res = [''.join(i) for i in listA]
# Result
print("Final list: \n",res)

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

运行以上代码,将得到以下结果 −

Given list :
[('M', 'o', 'n'), ('d', 'a', 'y'), ('7', 'pm')]
Final list:
['Mon', 'day', '7pm']

使用 map 和 join

我们将采用与上述类似的方法,但使用 map 函数来应用 join 方法。最后,使用 list 方法将结果封装在列表内。

示例

 立即演示

listA = [('M','o','n'), ('d','a','y'), ('7', 'pm')]
# Given list
print("Given list : \n", listA)
res = list(map(''.join, listA))
# Result
print("Final list: \n",res)

输出

运行以上代码,将得到以下结果 −

Given list :
[('M', 'o', 'n'), ('d', 'a', 'y'), ('7', 'pm')]
Final list:
['Mon', 'day', '7pm']

更新于: 20-May-2020

613 次浏览

开启你的 职业

完成课程,获得认证

立即开始
广告