📜  Python - 来自给定字符的 K 长度组合

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

Python - 来自给定字符的 K 长度组合

给定一个字符串,以单行方式生成 K 个长度的组合。

方法 #1:使用itertools.product() + join() + map()

该任务可以由 product() 使用重复参数执行,但返回结果在单个字符的元组列表中。这些都可以使用 join() 和 map() 连接起来。

Python3
# Python3 code to demonstrate working of 
# K length Combinations from given characters shorthand
# Using itertools.product() + join() + map()
from itertools import product
  
# initializing string
test_str = 'gf4g'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing K 
K = 2
  
# map and join() used to change return data type
res = list(map(''.join, product(test_str, repeat = K)))
      
# printing result 
print("The generated Combinations : " + str(res))


Python3
# Python3 code to demonstrate working of 
# K length Combinations from given characters shorthand
# Using itertools.product() + join() + map()
from itertools import product
  
# initializing string
test_str = 'gfg'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing K 
K = 2
  
# list comprehension + join() used to change return data type
res = [''.join(ele) for ele in product(test_str, repeat = K)]
      
# printing result 
print("The generated Combinations : " + str(res))


输出:

方法 #2:使用 itertools.product() + 列表理解

在这种情况下,列表理解用于连接元素的任务。

蟒蛇3

# Python3 code to demonstrate working of 
# K length Combinations from given characters shorthand
# Using itertools.product() + join() + map()
from itertools import product
  
# initializing string
test_str = 'gfg'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing K 
K = 2
  
# list comprehension + join() used to change return data type
res = [''.join(ele) for ele in product(test_str, repeat = K)]
      
# printing result 
print("The generated Combinations : " + str(res))

输出: