将值插入到列表中

2024-09-30 09:22:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在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) 

感谢您的帮助


Tags: to代码列表ifusecountnotdouble
2条回答

问题在于:

while X != 1:
    resultList = [];
    #etc

您正在使用循环的每次迭代重新创建列表。因此,它在最后只有一个值,即在最后一次迭代中唯一插入的值

把任务从循环中去掉,就像这样:

resultList = [];
while X != 1:
    #etc

…解决了问题

另外,请注意,您在这里所做的工作是不必要的:

    elif not X % 2:
    X = X // 2

你不必重复和颠倒你原来的状态。您只需将其设为else

if X % 2:
    X = 3 * X + 1
else:
    X = X // 2

while循环的每次迭代中,您都会创建resultList列表的新实例

while X != 1:
    resultList = [];
...

应替换为

resultList = [];
while X != 1:
    ...

要在list的末尾添加新元素,可以使用append方法。就像

resultList = [];
while X != 1:
    if X % 2:
        X = 3 * X + 1
    else:
        X = X // 2 #important to use double slash to have a integer division
    print(X)
    resultList.append(X)

相关问题 更多 >

    热门问题