我有一個整數串列,我想在 while 回圈的每次迭代中為串列中的每個整數加 1。更具體地說,我想對串列的整數一個一個(從左到右)執行此操作,而不是一次全部執行此操作,并在其條件變為 False 時立即停止回圈,即使這意味著在結束之前停止串列。
首先,我嘗試了以下方法:
def myfunction(someinput):
myintegerlist = [0, 0, 0]
while sum(myintegerlist) < someinput:
myintegerlist[0:] = [x 1 for x in myintegerlist[0:]]
return myintegerlist, sum(myintegerlist)
這不符合我的要求,因為它同時將 1 添加到串列中的所有整數。因此,如果 someinput = 4,它回傳 6 作為總和并回傳 [2, 2, 2] 作為串列,而我希望它在超過輸入數字之前停在 [2, 1, 1] 處。所以我嘗試了
while sum(myintegerlist) < someinput:
myintegerlist[indexplace] = [x 1 for x in myintegerlist[indexplace]]
indexplace = 1
這只是一個猜測,并拋出“TypeError:'int' object is not iterable”。但是我被困在如何逐個瀏覽串列項并向它們添加1。有沒有一種很好的方法可以在每次迭代時逐步在串列中移動?還是我應該嘗試完全不同的東西?
uj5u.com熱心網友回復:
在 while 回圈期間跟蹤需要添加 1 的索引:
def myfunction(someinput):
myintegerlist = [0, 0, 0]
increment_index = 0 # next place to add 1
while sum(myintegerlist) < someinput:
myintegerlist[increment_index % len(myintegerlist)] = 1 # add 1 to the element, modulo length of the list to keep the index in range
increment_index = 1
return myintegerlist, sum(myintegerlist)
print(myfunction(4))
結果:
([2, 1, 1], 4)
uj5u.com熱心網友回復:
通常,為了迭代串列中的值,您只需使用
for value in myintegerlist:
# ...
但這不允許您直接更改串列中的值。
您必須在串列的索引上創建一個回圈。
for i in range(len(myintegerlist)):
value = myintegerlist[i]
特別是,通過分配給myintegerlist[i]您可以更改串列中的值。
for i in range(len(myintegerlist)):
value = myintegerlist[i]
myintegerlist[i] = new_value
現在您需要一個額外的步驟,因為您不只是想迭代每個串列索引一次,而是可能多次迭代,直到滿足條件。為了保持迭代繼續進行,您可以使用模塊中的cycle函式itertools。
from itertools import cycle
for i in cycle(range(len(myintegerlist))):
# i = 0, 1, 2, 0, 1, 2, 0, 1, ...
現在,您只需將 1 添加到當前串列索引處的值,如果值的總和已達到所需數量,則中斷回圈:
for i in cycle(range(len(myintegerlist))):
if sum(myintegerlist) >= someinput:
break
myintegerlist[i] = 1
uj5u.com熱心網友回復:
每次都從0. someinput如果是一個很大的數字,太多無意義的迭代。
def get_els(sum_value: int, num_of_els: int = 3) -> tuple:
_list = [int(sum_value / num_of_els)] * num_of_els
if sum(_list) == sum_value:
return _list, sum_value
while True:
for idx in range(0, num_of_els):
_list[idx] = 1
if sum(_list) == sum_value:
return _list, sum_value
print(get_els(2))
print(get_els(4))
print(get_els(5))
print(get_els(10))
print(get_els(20))
輸出:
([1, 1, 0], 2)
([2, 1, 1], 4)
([2, 2, 1], 5)
([4, 3, 3], 10)
([7, 7, 6], 20)
此外,如果串列的長度只有 3 個元素,則根本不需要回圈:
def get_els(sum_value: int) -> tuple:
_list = [int(sum_value / 3)] * 3
if sum_value % 3 == 0:
return _list, sum_value
if sum_value % 3 > 1:
_list[0] = 1
_list[1] = 1
else:
_list[0] = 1
return _list, sum_value
uj5u.com熱心網友回復:
這更快
def myfunction(someinput):
myintegerlist = [0, 0, 0]
n=len(myintegerlist)
_sum=0
while 1:
for i in range(n):
myintegerlist[i] =1
_sum =1
if _sum == someinput:
return myintegerlist, sum(myintegerlist)
print(myfunction(20))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/515890.html
標籤:Python列表迭代
上一篇:洗掉串列中數字的倍數
