将 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)输出
运行以上代码,将得到以下结果 −
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']
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP