📜  Python - 组连接直到 K

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

Python - 组连接直到 K

给定字符串列表,在组中执行连接直到 K。

方法:使用循环 + join() + 列表推导

这是可以执行此任务的一种方式。在此,我们将部分字符串构造成列表,然后使用 join() 和列表推导执行各个列表的连接。

Python3
# Python3 code to demonstrate working of 
# Group concatenate Till K 
# Using loop + join() + list comprehension
  
# initializing lists
test_list = ["Gfg", "is", "Best", None, "I", "Love", None, "Gfg"]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing K 
K = None
  
# all() to encapsulate whole logic into one expression
res = [[]]
for sub in test_list:
      
    # checking for K value, and performing append to 
    # latest list 
    if sub != K:
        res[-1].append(sub)
    else:
          
        # constructing new list if new group
        res.append([])
  
# Joining all groups 
fin_res = [' '.join(ele) for ele in res]
  
# printing result 
print("Concatenated Groups : " + str(fin_res))


输出
The original list : ['Gfg', 'is', 'Best', None, 'I', 'Love', None, 'Gfg']
Concatenated Groups : ['Gfg is Best', 'I Love', 'Gfg']