Python – 连续K个元素加入List
有时,在使用Python列表时,我们可能会遇到需要将每 K 个字符连接到一个集合中的问题。这种类型的应用程序可以在许多领域都有用例,例如日间和竞争性编程。让我们讨论可以执行此任务的某些方式。
方法#1:使用列表推导
这是可以执行此任务的方式之一。在此,我们遍历列表并使用列表切片连接元素并返回聚合列表。
# Python3 code to demonstrate
# Consecutive K elements join in List
# using List comprehension
# Initializing list
test_list = ['g', 'f', 'g', 'i', 's', 'b', 'e', 's', 't']
# printing original list
print("The original list is : " + str(test_list))
# Initializing K
K = 3
# Consecutive K elements join in List
# using List comprehension
res = [ "".join(test_list[idx : idx + K]) for idx in range(len(test_list) - K + 1) ]
# printing result
print ("List after consecutive joining : " + str(res))
输出 :
The original list is : [‘g’, ‘f’, ‘g’, ‘i’, ‘s’, ‘b’, ‘e’, ‘s’, ‘t’]
List after consecutive joining : [‘gfg’, ‘fgi’, ‘gis’, ‘isb’, ‘sbe’, ‘bes’, ‘est’]
方法#2:使用循环
这是执行此任务的粗暴方式。这类似于上面的方法,只是使用循环对字符串进行迭代,使任务更加冗长乏味。
# Python3 code to demonstrate
# Consecutive K elements join in List
# using loop
# Initializing list
test_list = ['g', 'f', 'g', 'i', 's', 'b', 'e', 's', 't']
# printing original list
print("The original list is : " + str(test_list))
# Initializing K
K = 3
# Consecutive K elements join in List
# using loop
res = []
for idx in range(0, len(test_list) - K + 1):
res.append("".join(test_list[idx : idx + K]))
# printing result
print ("List after consecutive joining : " + str(res))
输出 :
The original list is : [‘g’, ‘f’, ‘g’, ‘i’, ‘s’, ‘b’, ‘e’, ‘s’, ‘t’]
List after consecutive joining : [‘gfg’, ‘fgi’, ‘gis’, ‘isb’, ‘sbe’, ‘bes’, ‘est’]