簡體   English   中英

排列后如何從相鄰的元組中打印值?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM