请帮助任何人!我正试图使用for循环打印列表,但我收到了这个错误,我对长生不老药很陌生,不知道如何解决这个
defmodule Todos do
def matrix_of_sum do
[
[21 ,"na", "na", "na", 12],
["na", "na", 12, "na", "na"],
["na", "na", "na", "na", "na"],
[17, "na", "na", "na", "na"],
["na", 22, "na", "na", "na"]
]
end
# print the rows and colums off the tuple in elixir
def print_list do
for i <- 0..4 do
for j <- 0..4 do
if matrix_of_sum[i][j] != "na" do
IO.puts matrix_of_sum[i][j]
end
end
end
end
end
#错误
** (ArgumentError) the Access calls for keywords expect the key to be an atom, got: 0
(elixir 1.14.0) lib/access.ex:313: Access.get/3
(todos 0.1.0) lib/todos.ex:15: anonymous fn/3 in Todos.print_list/0
(elixir 1.14.0) lib/enum.ex:4299: Enum.reduce_range/5
(todos 0.1.0) lib/todos.ex:14: anonymous fn/2 in Todos.print_list/0
(elixir 1.14.0) lib/enum.ex:4299: Enum.reduce_range/5
(todos 0.1.0) lib/todos.ex:13: Todos.print_list/0
iex:24: (file)
在Elixir中,list[index]
不能使用Access
行为访问列表。
你可以使用Enum.at/2
,比如:
matrix_of_sum |> Enum.at(i) |> Enum.at(j)
但这将是低效的:Elixir列表是链表,通过索引访问具有线性成本。
相反,您想要的是直接在列表上使用for
:
for row <- matrix_of_sum, cell <- row do
if cell != "na" do
IO.puts(cell)
end
end
这个错误之所以有点令人困惑,是因为Access
试图将列表读取为关键字列表:然后它需要i
是原子键,而不是整数。