python - 未将元素添加到 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]
"""
解决方案
您需要将值分配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]
推荐阅读
- python - 开发我自己的太空入侵者版本。我正在尝试找到一种方法来循环我的开火按钮,以便在按住时每 0.5 秒开火一次
- variables - 如何使用变量来避免为工作表中的所有列创建一组变量?
- html - 有没有办法在 qml 文本中使用多种字体大小进行垂直排序?
- node.js - MongoDB 在子文档上找到重叠的日期范围
- python - 如何在 Python 中使用 Selenium 从具有隐藏元素的动态折叠表中提取数据
- html - 如何在 angular4 路由中设置静态 url。this.router.navigate('http://xxxxxx.com/abx/xyz') 像这样,
- menu - Facebook Messenger 持久菜单从 web_url 发送有效负载
- php - 如何在 PHPUnit 中运行特定文件?
- c# - 在viewmodel中使用IValueConverter或字符串属性将数字转换为字符串?
- html - 如何用容器类为盒子着色?