首页 > 解决方案 > 未将元素添加到 for 循环中的列表

问题描述

为什么用户给出的元素没有被添加到列表中?相反,这份名单正在增加。

list1 =[]
print("How much numbers")
x =int(input())
print("input numbers:")
for n in range(x):
        int(input())
        y =list1.append(n)


print(list1)   



"""
output:

[0,1,2,3]
"""

标签: pythonlistfor-loop

解决方案


您需要将值分配int(input(..))给一个变量,并将该变量附加到列表中list1,以便您的代码工作

list1 =[]
print("How much numbers")
x =int(input())
print("input numbers:")
for n in range(x):
    #Take input and assign to z
    z = int(input())
    #Append z to list
    y = list1.append(z)

print(list1)

输出将是

How much numbers
4
input numbers:
1
2
3
4
[1, 2, 3, 4]

推荐阅读