[英]python for and while loop for tuples
我是python的初學者,想知道為什么此功能不起作用。 在語法上是正確的。
該函數應該收集每個奇數元組項,並且我使用了如下的for循環:
def oddTuples(aTup):
result = ()
for i in aTup:
if i % 2 == 0:
result += (aTup[i],)
return result
這是使用while循環的“正確”答案。
def oddTuples(aTup):
# a placeholder to gather our response
rTup = ()
index = 0
# Idea: Iterate over the elements in aTup, counting by 2
# (every other element) and adding that element to
# the result
while index < len(aTup):
rTup += (aTup[index],)
index += 2
return rTup
如果有人可以幫助我,將不勝感激!
更新
好的,我遇到了問題,通過“ i”,我只是在該元組中收集實際值。 我已經解決了這個問題,但是這段代碼僅捕獲了一些奇異的項目,而不是全部。
def oddTuples(aTup):
result = ()
for i in aTup:
index = aTup.index(i)
if index % 2 == 0:
result += (aTup[index],)
return result
由於語法上也是正確的 ,所以我沒有aTup
抓住它,但是您遇到的錯誤是由於您遍歷了元組( aTup
)的objects
而不是索引。 看這里:
for i in aTup: # <-- For each *object* in the tuple and NOT indices
if i % 2 == 0:
result += (aTup[i],)
要解決此問題,請在aTup
使用range()
和len()
,以使其遍歷元組的索引,然后相應地更改if
語句:
for i in range(len(aTup)):
if aTup[i] % 2 == 0:
result += (aTup[i],)
另一種解決方案是保留對象迭代,但將對象直接附加到result
元組而不是建立索引:
for i in aTup:
if i % 2 == 0:
result += (i,)
希望這些幫助!
您的for循環迭代aTup中的值,而不是值的索引。
似乎您希望您的代碼遍歷值的索引或遍歷從0開始到元組長度減去1的數字范圍,然后使用該數字作為索引將值從元組中拉出。
原因是您沒有使用索引。在下面的代碼中,我不是索引,而是元組中的元素,但是您在調用iTup [i]並假設i是一個不存在的索引。 以下代碼可以正常工作-無需執行aTup [i]或range。
def oddTuples(aTup):
result = ()
for i in aTup:
if i % 2 == 0:
result += (i,)
return result
簡單來說,如果您的元組是
tup = (1, 2, 3, 4, 5 , 1000);
當您的代碼檢查每個項目是否為%2 == 0或不是您想要的內容時,從您的描述中,您只需要索引為奇數的項目
因此,如果您嘗試上面的元組,則會收到以下錯誤: IndexError: tuple index out of range
,因為對於1000,它滿足您的條件,並且會執行if中的說明,嘗試添加aTup(1000)(輸入元組中索引1000的元素) 不存在,因為該元組僅是resultTuple的6個元素
為了使此for循環起作用,可以使用以下方法
def oddTuples(aTup):
result = ()
for i in aTup:
index = tup.index(i) # getting the index of each element
if index % 2 == 0:
result += (aTup[index],)
print(aTup[index])
return result
# Testing the function with a tuple
if __name__ == "__main__":
tup = (1, 2, 3, 7, 5, 1000, 1022)
tup_res = oddTuples(tup)
print(tup_res)
其結果將是
1
3
5
1022
(1, 3, 5, 1022)
Process finished with exit code 0
嘗試更換
def oddTuples(aTup):
result = ()
for i in aTup:
index = aTup.index(i)
if index % 2 == 0:
result += (aTup[index],)
return result
用
def oddTuples(aTup):
result = ()
for i in aTup:
index = aTup.index(i)
result += (aTup[index],)
return result
為了解決您的問題,它只執行偶數編號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.