我尝试在while循环的一部分的列表中插入值,而不是插入最后一个值,而是替换之前的值,因此列表将始终只有一个值!,我正在尝试添加值而不是替换它们,下面是我的代码:
while X != 1:
resultList = [];
#extList = []
count += 1
if X % 2:
X = 3 * X + 1
elif not X % 2:
X = X // 2 #important to use double slash to have a integer division
print(X)
resultList.insert(count-1, X)
#print("the resultList is " + str(resultList))
#extList.extend(resultList)
print("The inputValue "+str(originalValue)+" took "+str(count)+" calculations to reach 1")
print (resultList)
感谢您的帮助
问题在于:
您正在使用循环的每次迭代重新创建列表。因此,它在最后只有一个值,即在最后一次迭代中唯一插入的值
把任务从循环中去掉,就像这样:
…解决了问题
另外,请注意,您在这里所做的工作是不必要的:
你不必重复和颠倒你原来的状态。您只需将其设为
else
在
while
循环的每次迭代中,您都会创建resultList
列表的新实例应替换为
要在
list
的末尾添加新元素,可以使用append
方法。就像相关问题 更多 >
编程相关推荐