Python|将元组记录转换为单个字符串
有时,在处理数据时,我们可能会遇到元组记录的问题,我们需要将其更改为逗号分隔的字符串。这些可以是关于姓名的数据。这类问题在 Web 开发领域有其应用。让我们讨论一些可以解决这个问题的方法。
方法 #1:使用join()
+ 列表推导
在这种方法中,我们只是遍历列表元组元素并执行它们之间的连接,以空格分隔,将它们连接为单个记录字符串。
# Python3 code to demonstrate working of
# Convert tuple records to single string
# Using list comprehension + join()
# Initializing list
test_list = [('Manjeet', 'Singh'), ('Nikhil', 'Meherwal'), ('Akshat', 'Garg')]
# printing original list
print("The original list is : " + str(test_list))
# Convert tuple records to a single string
# Using list comprehension + join()
res = ', '.join([' '.join(sub) for sub in test_list])
# printing result
print("The string after tuple conversion: " + res)
输出 :
The original list is : [('Manjeet', 'Singh'), ('Nikhil', 'Meherwal'), ('Akshat', 'Garg')]
The string after tuple conversion: Manjeet Singh, Nikhil Meherwal, Akshat Garg
方法 #2:使用map() + join()
此方法执行此任务类似于上述函数。不同之处在于它使用map()
来扩展连接逻辑而不是列表理解。
# Python3 code to demonstrate working of
# Convert tuple records to single string
# Using map() + join()
# Initializing list
test_list = [('Manjeet', 'Singh'), ('Nikhil', 'Meherwal'), ('Akshat', 'Garg')]
# printing original list
print("The original list is : " + str(test_list))
# Convert tuple records to a single string
# Using map() + join()
res = ', '.join(map(" ".join, test_list))
# printing result
print("The string after tuple conversion: " + res)
输出 :
The original list is : [('Manjeet', 'Singh'), ('Nikhil', 'Meherwal'), ('Akshat', 'Garg')]
The string after tuple conversion: Manjeet Singh, Nikhil Meherwal, Akshat Garg