Python –字符的连续重复
有时,在处理字符列表时,我们可能会遇到需要连续重复字符的问题。这可以在许多领域中应用。让我们讨论可以执行此任务的某些方式。
方法#1:使用列表推导
这是可以执行此任务的方式之一。在这种情况下,我们执行一种蛮力的方式来执行,但是通过将每个字符乘以大小来单行执行。
# Python3 code to demonstrate working of
# Consecutive Repetition of Characters
# 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 Repetition of Characters
# Using list comprehension
res = [sub for ele in test_list for sub in [ele] * K]
# printing result
print("The list after Consecutive Repetition is : " + str(res))
The original list is : [‘g’, ‘f’, ‘g’, ‘i’, ‘s’, ‘b’, ‘e’, ‘s’, ‘t’]
The list after Consecutive Repetition is : [‘g’, ‘g’, ‘g’, ‘f’, ‘f’, ‘f’, ‘g’, ‘g’, ‘g’, ‘i’, ‘i’, ‘i’, ‘s’, ‘s’, ‘s’, ‘b’, ‘b’, ‘b’, ‘e’, ‘e’, ‘e’, ‘s’, ‘s’, ‘s’, ‘t’, ‘t’, ‘t’]
方法#2:使用chain() + repeat()
上述功能的组合可以用来解决这个问题。在此,我们使用repeat() 执行重复任务,并使用chain() 执行结果构造。
# Python3 code to demonstrate working of
# Consecutive Repetition of Characters
# Using chain() + repeat()
from itertools import chain, repeat
# 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 Repetition of Characters
# Using chain() + repeat()
res = list(chain.from_iterable(repeat(chr, K) for chr in test_list))
# printing result
print("The list after Consecutive Repetition is : " + str(res))
The original list is : [‘g’, ‘f’, ‘g’, ‘i’, ‘s’, ‘b’, ‘e’, ‘s’, ‘t’]
The list after Consecutive Repetition is : [‘g’, ‘g’, ‘g’, ‘f’, ‘f’, ‘f’, ‘g’, ‘g’, ‘g’, ‘i’, ‘i’, ‘i’, ‘s’, ‘s’, ‘s’, ‘b’, ‘b’, ‘b’, ‘e’, ‘e’, ‘e’, ‘s’, ‘s’, ‘s’, ‘t’, ‘t’, ‘t’]