Python - 字符串列表中的增量切片连接
给定一个 String 列表,通过增加每个字符串的大小来执行串联字符串的任务。
例子:
Input : test_list = [‘gfg’, ‘for’, ‘all’, ‘geeks’],
Output : gfoallgeek
Explanation : g, fo, all, geek -> concatenated from each string [ increasing order ].
Input : test_list = [‘gfg’, ‘for’, ‘geeks’],
Output : gfogee
Explanation : g, fo, gee -> concatenated from each string [ increasing order ].
方法#1:使用循环+切片
在这种情况下,使用循环,通过在每次传递时增加计数器的切片来迭代和连接每个字符串。
Python3
# Python3 code to demonstrate working of
# Incremental Slice concatenation in String list
# Using loop + slicing
# initializing list
test_list = ['gfg', 'for', 'all', 'geeks']
# printing original list
print("The original list is : " + str(test_list))
res = ''
for idx in range(len(test_list)):
# Incremental slicing
res += test_list[idx][:idx + 1]
# printing result
print("Incremental sliced concatenated string : " + str(res))
Python3
# Python3 code to demonstrate working of
# Incremental Slice concatenation in String list
# Using join() + list comprehension
# initializing list
test_list = ['gfg', 'for', 'all', 'geeks']
# printing original list
print("The original list is : " + str(test_list))
# join performs concatenation
res = ''.join([test_list[idx][:idx + 1] for idx in range(len(test_list))])
# printing result
print("Incremental sliced concatenated string : " + str(res))
输出
The original list is : ['gfg', 'for', 'all', 'geeks']
Incremental sliced concatenated string : gfoallgeek
方法 #2:使用 join() + 列表理解
其中,连接任务使用 join() 完成,迭代任务使用列表理解完成以提供速记。
蟒蛇3
# Python3 code to demonstrate working of
# Incremental Slice concatenation in String list
# Using join() + list comprehension
# initializing list
test_list = ['gfg', 'for', 'all', 'geeks']
# printing original list
print("The original list is : " + str(test_list))
# join performs concatenation
res = ''.join([test_list[idx][:idx + 1] for idx in range(len(test_list))])
# printing result
print("Incremental sliced concatenated string : " + str(res))
输出
The original list is : ['gfg', 'for', 'all', 'geeks']
Incremental sliced concatenated string : gfoallgeek