用for循环填充列表 [英] Fill a List with a for-loop
问题描述
new_data = []
for data< - old_data do
new_data = List.insert_at(new_data,-1,data)
end
在这个操作之后,即使循环执行了N次,我的 new_data
列表仍然是空的。
您可以将理解结果分配给:
new_data = for data< - old_data do
data
end
:
new_data = List.insert_at(new_data,-1,data)
new_data
变量对理解的范围是本地的。您可以使用以前的 new_data
值,但是您将无法重新绑定外部范围。这就是为什么 new_data
在理解之后仍然是 []
。范围规则在 http://elixir-lang.readthedocs.org /en/latest/technical/scoping.html
Why can't I fill a list with this simple for-loop?
new_data = []
for data <- old_data do
new_data = List.insert_at(new_data, -1, data)
end
After this operation my new_data
list is still empty, even though the loop is N times executed.
In Elixir, you can't mutate the value your variable is referencing as explained in Are Elixir variables really immutable?. For in this instance is not a "loop" it is a list comprehension.
You can assign to the result of a comprehension with:
new_data = for data <- old_data do
data
end
In your line:
new_data = List.insert_at(new_data, -1, data)
The new_data
variable is local to the scope of the comprehension. You can use your previous new_data
value, but you won't be able to rebind for the outside scope. Which is why new_data
is still []
after your comprehension. The scoping rules are explained in http://elixir-lang.readthedocs.org/en/latest/technical/scoping.html
这篇关于用for循环填充列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!