📜  Python|连续的前缀重叠连接

📅  最后修改于: 2022-05-13 01:55:08.365000             🧑  作者: Mango

Python|连续的前缀重叠连接

有时,在使用Python字符串时,我们可能需要在其中执行字符串列表中所有元素的连接的应用程序。如果我们需要在匹配的情况下将当前元素的后缀与 next 的前缀重叠,这可能会很棘手。让我们讨论可以执行此任务的某些方式。

方法 #1:使用循环 + endswith() + join() + list comprehension + zip()
上述功能的组合可用于执行此任务。在此,我们使用循环来实现使用endswith() 的join/no join 逻辑。如果是连接,则使用 join() 执行。整个逻辑在列表理解中编译。

# Python3 code to demonstrate working of 
# Consecutive prefix overlap concatenation
# Using endswith() + join() + list comprehension + zip() + loop
  
def help_fnc(i, j):
    for ele in range(len(j), -1, -1):
        if i.endswith(j[:ele]):
            return j[ele:]
  
# initializing list
test_list = ["gfgo", "gone", "new", "best"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Consecutive prefix overlap concatenation
# Using endswith() + join() + list comprehension + zip() + loop
res = ''.join(help_fnc(i, j) for i, j in zip([''] + 
                           test_list, test_list))
  
# printing result 
print("The resultant joined string : " + str(res)) 
输出 :
The original list is : ['gfgo', 'gone', 'new', 'best']
The resultant joined string : gfgonewbest

方法 #2:使用reduce() + lambda + next()
上述方法的组合也可以用来解决这个问题。在此,我们使用 next() 和 endswith 执行重叠任务,其余任务使用 reduce() 和 lambda 执行。

# Python3 code to demonstrate working of 
# Consecutive prefix overlap concatenation
# Using reduce() + lambda + next()
  
# initializing list
test_list = ["gfgo", "gone", "new", "best"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Consecutive prefix overlap concatenation
# Using reduce() + lambda + next()
res = reduce(lambda i, j: i + j[next(idx 
            for idx in reversed(range(len(j) + 1)) 
            if i.endswith(j[:idx])):], test_list, '', )
  
# printing result 
print("The resultant joined string : " + str(res)) 
输出 :
The original list is : ['gfgo', 'gone', 'new', 'best']
The resultant joined string : gfgonewbest