嘿,初学者,我有一个家庭作业,我有一个列表,为了更容易理解,我举了一个例子,现在让我们把列表= 1,2,4,6,5,9,if 4-2 > 2-1加到一个新的列表中,数字1,2,4,6-4不大于4-2,所以不要把6加到列表中,下面是我写的代码
lst4 = [1, 2, 4, 7] # Replace the assignment with other lists to test your code.
# Write the rest of the code for question 4 below here.
l=[]
for i in range(len(lst4)-2):
if abs(lst4[i]-lst4[i+1]) >= abs(lst4[i+1]-lst4[i+2]):
l.append(lst4[i])
l.append(lst4[i+1])
print(l) 我怎么才能让它工作呢?应该打印的正确列表是1,2,4,9我得到一个空列表
发布于 2021-10-27 20:48:35
保持一个运行计数器来跟踪列表中最后两个元素之间的当前差异可能会很有用。
lst4 = [1, 2, 4, 7]
def ListCreator(listy):
listy.sort()
diff = listy[1] - listy[0]
result = [listy[0], listy[1]]
for i in range (2, len(listy)):
if listy[i]-result[-1] > diff:
result.append(listy[i])
diff = result[-1] - result[-2]
return resulthttps://stackoverflow.com/questions/69745089
复制相似问题