![](/img/trans.png)
[英]How can I remove a tuple from a list if the tuple contains two "1" next to each other in Python?
[英]How to print values from a tuple next to each other after permutation?
任务:
给您一个字符串“ S”。 您的任务是按字典编排顺序打印字符串大小的所有可能排列。
输入格式:
一行包含空格分隔的字符串“ S”和整数值“ K”。
解释置换如何工作的示例代码(我稍后将使用其中之一):
>>> from itertools import permutations
>>> print permutations(['1','2','3'])
<itertools.permutations object at 0x02A45210>
>>>
>>> print list(permutations(['1','2','3']))
[('1', '2', '3'), ('1', '3', '2'), ('2', '1', '3'), ('2', '3', '1'),
('3', '1', '2'), ('3', '2', '1')]
>>>
>>> print list(permutations(['1','2','3'],2))
[('1', '2'), ('1', '3'), ('2', '1'), ('2', '3'), ('3', '1'), ('3',
'2')]
>>>
>>> print list(permutations('abc',3))
[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'),
('c', 'a', 'b'), ('c', 'b', 'a')]
输入样例:
哈克2
样本输出:
一个接一个:AC AH AK CA CH CK HA HC HK KA KC KH
说明:
字符串“ HACK”的所有可能的大小为2的排列都按字典顺序排序。
这是我的代码:
from itertools import permutations
S = input().split()
K = "".join(sorted(A[0].upper()))
C = int(A[1])
for i in permutations(S,C):
print(i)
但是输出为:('A','C')('A','H')('A','K')('C','A')('C','H') ('C','K')('H','A')('H','C')('H','K')('K','A')('K', 'C')('K','H')
如何以这种方式在没有括号和引号的情况下打印这些元组的元素?:AC AH AK一个接一个。
请注意,它必须在用户键入“ hack 3”或“ anything x”时起作用,其中x是排列组合中每个元素的元素数。
您可以使用str.join()
并像字符串一样打印它们:
from itertools import permutations
a = list(permutations('hack',2))
# In a more pythonic way you can do:
# a = permutations('hack', 2)
# Then you can include it in a foor loop
for k in a:
print("".join(k).upper(), end = " ")
输出:
HA HC HK AH AC AK CH CA CK KH KA KC
for i in permutations(S,C):
print(i)
至
for i in permutations(S,C):
for j in range(C):
print(i[j], end='')
我假设您正在使用Python 3。
from itertools import permutations
A = input().split()
B = "".join(sorted(A[0].upper()))
C = int(A[1])
a = list(permutations(B,C))
for k in a:
print("".join(k))
我们得到了它! 感谢@Chiheb Nexus!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.