为什么我的列表元素没有被转换为 int?
(为了更好地理解,我写了列表而不是实际的列表名称)
我正在从一个包含一个数字的文件中读取在每一行。然后我将其放入 list[]
并执行 list.append(line.replace("\n", "").strip())
时我写的函数 - list = inteles(list)
我尝试重新启动 vs code,但没有成功。
(I wrote list instead of the actual list names for better understanding)
I'm reading from a file with one number at each line. Then I made it into a list[]
and I did list.append(line.replace("\n", "").strip())
When executing the function I wrote - list = inteles(list)
I tried restarting vs code, but it didn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为当您说
for x in y
时,您得到的x
无法更改列表中真实x
的值。 (我相信除了修改类属性)要解决这个问题,只需进行列表理解:
Since when you say
for x in y
, thex
you get isn't able to change the value of the realx
in the list. (except with modifying class attributes I believe)To fix this, just do a list comprehension:
您没有更改原始列表的值,也没有创建新列表,您只是更改局部变量(到该函数)的值。如果要获取所有字符串都转换为整数的列表,则应在函数中创建一个新列表,并将更改后的局部变量附加到该本地列表,然后返回该本地列表。
下面是一个例子:
You are not changing the value of the original list, you are not creating a new list either, you are just changing the value of a local variable (to that function). If you want to get a list with all strings converted to a integer, you should create a new list in the function and append the changed local variable to that local list and then return that local list.
Below is a example of that:
为什么不
list.append(int(line.replace("\n", "").strip()))
Why not
list.append(int(line.replace("\n", "").strip()))