所以我寫了這個代碼,旨在從串列一起讓代碼組不同的號碼共n: int組
編輯如果您不明白代碼的目的是什么,請查看評論,我已經在那里解釋過了。謝謝:)
def calcdifference(lst: list):
for x in lst:
return (x -= x)
print(calcdifference(lst=[4,5,6,4,3,2,3,4,5]))
def grouping(lst: list, n: int):
if calcdifference(x) in list == max(calcdifference(x)):
lst.append(x)
print(grouping(lst=[4,5,6,4,3,2,3,4,5]))
n: int 表示單個串列允許的組數,因此如果 n 為 3,則數字將被分組為 (x,...), (x,....) (x,...) 如果n = 2,數字將被分組為 (x,..),(x,...)。
但是,我的代碼在 n 個元素的串列中列印出所有可能的組合。但它不會將數字組合在一起。所以我想要的是:例如,如果輸入是
[10,12,45,47,91,98,99]
如果 n = 2,輸出將是
[10,12,45,47] [91,98,99]
如果 n = 3,輸出將是
[10,12] [45,47] [91,98,99]
我應該對我的代碼進行哪些更改?
注意:請不要使用內置函式或匯入,因為我想使用盡可能少的內置函式
重要提示:代碼應該能夠為n >= len(lst)提供的每個串列列印組合
uj5u.com熱心網友回復:
您可以嘗試以下操作:
def grouping(lst, n):
diff = enumerate((abs(x - y) for x, y in zip(lst, lst[1:])), start=1)
cut = sorted(x[0] for x in sorted(diff, reverse=True, key=lambda x: x[1])[:n-1])
cut = [0, *cut, len(lst)] # add 0 and last index
return [lst[i:j] for i, j in zip(cut, cut[1:])] # return slices
lst = [10,12,45,47,91,98,99]
print(grouping(lst, 2))
print(grouping(lst, 3))
print(grouping(lst, 4))
輸出:
[[10, 12, 45, 47], [91, 98, 99]]
[[10, 12], [45, 47], [91, 98, 99]]
[[10, 12], [45, 47], [91], [98, 99]]
誠然,它非常復雜,而且可能不那么像 Python 那樣。可能有更有效的方法。無論如何,一些解釋如下......
在第一行中,diff是含有一個元組(排序的)串列(i, d),使得lst具有差d之間i-1個項和i個項。
第二行比較復雜。首先,sorted(diff, reverse=True, key=lambda x: x[1])根據第二個元素對那些元組進行排序,即代表最高跳躍的元組在前。
然后sorted(...)[:n-1]選擇前 n-1 個元組。這些將是要使用的 n-1 個切割。
生成器理解(x[0] for x in ...)只是選擇每個元組的第一項;即,我們不再需要差異。
然后再次sorted(...)對這些剪切位置進行排序,這將使后續行作業。
如果您lambda出于某種原因不愿意使用(實際上operator.itemgetter(1)比 更好lambda x: x[1]),您可以為此創建一個自定義函式。
def get_1st(x):
return x[1]
def grouping(lst, n):
diff = enumerate((abs(x - y) for x, y in zip(lst, lst[1:])), start=1)
cut = sorted(x[0] for x in sorted(diff, reverse=True, key=get_1st)[:n-1])
cut = [0, *cut, len(lst)] # add 0 and last index
return [lst[i:j] for i, j in zip(cut, cut[1:])] # return slices
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/353104.html
