Python – 异构列表中的字符串连接
有时,在使用Python时,我们可能会遇到需要查找字符串连接的问题。这个问题比较容易解决。但是如果我们有混合的数据类型,这可能会变得复杂。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环+条件
我们可以使用蛮力方法来输入种姓检查每个元素,如果它是一个字符串,我们将它连接起来。这可以确保只有字符串被连接,因此可以解决问题。
Python3
# Python3 code to demonstrate working of
# String concatenation in Heterogeneous list
# using loop + conditions
# initializing list
test_list = [5, 6, "gfg ", 8, (5, 7), ' is', 9, ' best']
# printing original list
print("The original list is : " + str(test_list))
# String concatenation in Heterogeneous list
# using loop + conditions
res = ''
for ele in test_list:
if type(ele) == str:
res += ele
# printing result
print("Concatenation of strings in list : " + str(res))
Python3
# Python3 code to demonstrate working of
# String concatenation in Heterogeneous list
# using join() + isinstance()
# initializing list
test_list = [5, 6, "gfg ", 8, (5, 7), ' is', 9, ' best']
# printing original list
print("The original list is : " + str(test_list))
# String concatenation in Heterogeneous list
# using join() + isinstance()
res = "".join(filter(lambda i: isinstance(i, str), test_list))
# printing result
print("Concatenation of strings in list : " + str(res))
输出 :
The original list is : [5, 6, 'gfg ', 8, (5, 7), ' is', 9, ' best']
Concatenation of strings in list : gfg is best
方法 #2:使用 join() + isinstance()
这个问题也可以使用 join() 的内置函数来解决,它还支持使用 isinstance() 的实例过滤器,它可以输入字符串,从而解决问题。
Python3
# Python3 code to demonstrate working of
# String concatenation in Heterogeneous list
# using join() + isinstance()
# initializing list
test_list = [5, 6, "gfg ", 8, (5, 7), ' is', 9, ' best']
# printing original list
print("The original list is : " + str(test_list))
# String concatenation in Heterogeneous list
# using join() + isinstance()
res = "".join(filter(lambda i: isinstance(i, str), test_list))
# printing result
print("Concatenation of strings in list : " + str(res))
输出 :
The original list is : [5, 6, 'gfg ', 8, (5, 7), ' is', 9, ' best']
Concatenation of strings in list : gfg is best