📜  Python -字符重复字符串组合

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

Python -字符重复字符串组合

鉴于数字的字符串列表和列表,任务是写一个Python程序由列表中的每个号码重复每个字符串的每个字符生成所有可能的字符串。

方法 #1:使用join() +循环+列表推导+ *运算符

在这种情况下,构造每个字符串的任务是使用 join() 完成的。 *运算符执行创建多个字符出现的任务。嵌套循环用于将每个数字与每个字符串组合起来。

Python3
# Python3 code to demonstrate working of
# Character repetition string combinations
# Using join() + nested loop + list comprehension + * operator
  
# initializing list
test_list = ["gfg", "is", "best"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# repeat list
rep_list = [3, 5, 2]
  
# * operator performs repetitions
# list comprehension encapsulates logic
res = [''.join(sub * ele1 for sub in ele2)
       for ele1 in rep_list for ele2 in test_list]
  
# printing result
print("All repetition combinations strings : " + str(res))


Python3
# Python3 code to demonstrate working of
# Character repetition string combinations
# Using product() + join() + loop
from itertools import product
  
# initializing list
test_list = ["gfg", "is", "best"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# repeat list
rep_list = [3, 5, 2]
  
# * operator performs repetitions
# list comprehension encapsulates logic
res = [''.join(sub * ele1 for sub in ele2)
       for ele2, ele1 in product(test_list, rep_list)]
  
# printing result
print("All repetition combinations strings : " + str(res))


输出:

方法#2:使用product() + join() + loop

在此方法中通过使用 product() 方法避免了用于生成对的嵌套循环。其余所有功能与上述方法相同。

蟒蛇3

# Python3 code to demonstrate working of
# Character repetition string combinations
# Using product() + join() + loop
from itertools import product
  
# initializing list
test_list = ["gfg", "is", "best"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# repeat list
rep_list = [3, 5, 2]
  
# * operator performs repetitions
# list comprehension encapsulates logic
res = [''.join(sub * ele1 for sub in ele2)
       for ele2, ele1 in product(test_list, rep_list)]
  
# printing result
print("All repetition combinations strings : " + str(res))

输出: