我正在撰寫一個程式來確定用戶輸入資料集的圓錐序列,例如 - [0000,1,2222,9999],
我正在努力僅使用 4 位分類而不是典型的 8/16 二進制方法對圓錐序列進行排序。
我試過這個:
for t in permutations(numbers, 4):
print(''.join(t))
但它不會為輸入的資料分配唯一值,而是覆寫以前的值。
我該怎么做呢?
uj5u.com熱心網友回復:
由于您的串列僅包含數字 0 到 9,并且您正在遍歷該串列,并在列印時列印內容,因此它只會列印 0 到 9。
由于正常十進制數字的所有可能組合(或更確切地說是排列,因為這是您要問的)只是數字 0 到 9999,您可以這樣做:
for i in range(10000):
print(i)
有關更多資訊,請參閱https://docs.python.org/3/library/functions.html#func-rangerange()。
但這不會將像“0”這樣的數字列印為“0000”。要做到這一點(在 Python 3 中,這可能是您應該使用的):
for i in range(10000):
print(f"{i:04d}")
有關f 字串的更多資訊,請參閱https://docs.python.org/3/reference/lexical_analysis.html#f-strings。
當然,如果需要對數字以外的東西進行排列,則不能使用此方法。你會做這樣的事情:
from itertools import permutations
xs = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
for t in permutations(xs, 4):
print(''.join(t))
見https://docs.python.org/3/library/itertools.html#itertools.permutations更多關于permutations()與區別combinations()。
uj5u.com熱心網友回復:
如果您想在將來更改某些資訊,您也可以執行以下操作:
import math
NUMBERS = [0,1,2,3,4,5,6,7,8,9]
DIGITS = 4
MAX_ITERS = int(math.pow(len(NUMBERS), DIGITS))
for i in range(MAX_ITERS):
print(f"{i:04d}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/342654.html
