问题是找出列表x中两个连续数字的和等于t,并返回不包含第二个数字的x列表


def trouble(x, t):
for i in range(0,len(x)):

if (x[i]+ x[i+1]) == t:
return x

else:
return None
answer = trouble([4,5,6,7], 9)
print(answer)

首先,它不是很清楚你实际上在问什么,你只是推了一个代码团和一个标题。假设你希望有人告诉你代码是否正确;事实并非如此。现在这真的只是看起来像一个家庭作业问题,所以我不会只是发布一个答案代码,但这里有一些可能有用的评论:

def trouble(x, t):
for i in range(0,len(x)): # Range starts at 0 even when not specified

if (x[i]+ x[i+1]) == t:
return x  
# You also want to remove the second number no ? 
# Hint: you could use slicing, or the list remove(elem) function

else:
# Because this is in the loop it will return immediately
# if the if condition fails (ie: you'll only ever
# look at the first element !
return None 
answer = trouble([4,5,6,7], 9)
print(answer)

这是你想要的吗?它删除第二个加起来等于t的值,并返回新列表。

def trouble(x, t):
x = list(x)
for i in range(0, len(x)-1):
if (x[i]+ x[i+1]) == t:
y = list(x) 
y.pop(i+1)
return y


else:
return None
answer = trouble([1,3,6], 9)
print(answer)

最新更新