Python|将字符串列表转换为连接的单个元素
有时,在使用Python时,我们可能会遇到一个问题,我们需要通过使用 delim 组合来执行将 String 列表的每个元素连接到 List 中的单个元素的任务。这种应用程序可以进入网络开发领域。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是执行此任务的一种方式。在此,我们使用循环对字符串列表进行迭代,并根据分隔符执行连接操作。
# Python3 code to demonstrate working of
# Convert String list to Joined Single element
# Using loop
# initializing list
test_list = ['gfg', 'is', 'best']
# printing original list
print("The original list is : " + str(test_list))
# initializing delim
delim = "-"
# Convert String list to Joined Single element
# Using loop
res = ''
for idx in range(len(test_list)-1):
res = res + test_list[idx] + delim
if len(test_list) > 0:
res = res + test_list[-1]
res = [res]
# printing result
print("String after performing join : " + str(res))
输出 :
The original list is : ['gfg', 'is', 'best']
String after performing join : ['gfg-is-best']
方法 #2:使用join()
+ 列表推导
也可以使用上述功能的组合来执行此任务。在此,我们使用 join() 执行组合任务。逻辑是使用列表推导编译的。
# Python3 code to demonstrate working of
# Convert String list to Joined Single element
# Using join() + list comprehension
# initializing list
test_list = ['gfg', 'is', 'best']
# printing original list
print("The original list is : " + str(test_list))
# initializing delim
delim = "-"
# Convert String list to Joined Single element
# Using join() + list comprehension
res = [delim.join(test_list)]
# printing result
print("String after performing join : " + str(res))
输出 :
The original list is : ['gfg', 'is', 'best']
String after performing join : ['gfg-is-best']