我是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
如果有人可以帮助我,我将不胜感激!
更新
好吧,我遇到了问题,'我'我只是收集了那个元组中的真正价值。我已经解决了这个问题,但是这段代码只捕获了一些奇怪的物品,而不是所有物品....
def oddTuples(aTup):
result = ()
for i in aTup:
index = aTup.index(i)
if index % 2 == 0:
result += (aTup[index],)
return result
答案 0 :(得分:0)
我没有一次抓住它,因为它也是语法正确的,但你所遇到的错误是由于你迭代了元组的objects
( aTup
)而不是指数。见这里:
for i in aTup: # <-- For each *object* in the tuple and NOT indices
if i % 2 == 0:
result += (aTup[i],)
要解决此问题,请在range()
上使用len()
和aTup
,以便它反过来迭代元组的索引,并相应地更改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,)
希望有所帮助!
答案 1 :(得分:0)
你的for循环遍历aTup中的值,而不是值的索引。
看起来您希望您的代码迭代值的索引或通过从0开始并以元组的长度减1的数字结束的数字范围,然后使用该数字作为索引将值拉出元组。
答案 2 :(得分:0)
原因是你没有使用索引。在下面的代码中,我不是索引,而是元组中的元素,但是你正在调用aTup [i],假设我是一个不是的索引。 以下代码可以正常工作 - 无需执行aTup [i]或范围。
def oddTuples(aTup):
result = ()
for i in aTup:
if i % 2 == 0:
result += (i,)
return result
答案 3 :(得分:0)
简单来说,如果你的元组是
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
答案 4 :(得分: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
为了解决你的问题,只做偶数编号。