📌  相关文章
📜  Python - 按给定顺序连接字符串

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

Python - 按给定顺序连接字符串

给定一个字符串列表和顺序列表,按特定顺序执行字符串连接。

方法#1:使用循环

在此,我们在循环中迭代 order 元素,并以相似的顺序执行相似索引的字符串的串联。

Python3
# Python3 code to demonstrate working of 
# Concatenate Strings in Order
# Using loop
  
# initializing list
test_list = ["best", "Gfg", "for", "is", "geeks"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing join order 
sort_order = [1, 3, 0, 2, 4]
  
res = ''
for ordr in sort_order:
      
    # concatenating by order 
    res += test_list[ordr]
  
# printing result 
print("Ordered concatenation : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Concatenate Strings in Order
# Using join() + list comprehension
  
# initializing list
test_list = ["best", "Gfg", "for", "is", "geeks"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing join order 
sort_order = [1, 3, 0, 2, 4]
  
# join() performs concatenation
res = ''.join([test_list[ordr] for ordr in sort_order])
  
# printing result 
print("Ordered concatenation : " + str(res))


输出
The original list is : ['best', 'Gfg', 'for', 'is', 'geeks']
Ordered concatenation : Gfgisbestforgeeks

方法 #2:使用 join() + 列表理解

在这里,我们使用 join() 执行连接任务,列表理解用于顺序迭代。

蟒蛇3

# Python3 code to demonstrate working of 
# Concatenate Strings in Order
# Using join() + list comprehension
  
# initializing list
test_list = ["best", "Gfg", "for", "is", "geeks"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing join order 
sort_order = [1, 3, 0, 2, 4]
  
# join() performs concatenation
res = ''.join([test_list[ordr] for ordr in sort_order])
  
# printing result 
print("Ordered concatenation : " + str(res))


输出
The original list is : ['best', 'Gfg', 'for', 'is', 'geeks']
Ordered concatenation : Gfgisbestforgeeks