随机排列嵌套在另一个列表中的结构中的列表

时间:2018-11-11 15:19:08

标签: elixir

使用以下代码:

[
  %Quizz{
    question: "L'unità d' Italia",
    answers: [
      %{answer: 1900, result: false},
      %{answer: 1861, result: true},
      %{answer: 1848, result: false},
    ]
  },
  %Quizz{
    question: "La Rivoluzione Francese",
    answers: [
      %{answer: 1789, result: true},
      %{answer: 1818, result: false},
      %{answer: 1766, result: false},
    ]
  },
  %Quizz{
    question: "La scoperta dell'America",
    answers: [
      %{answer: 1280, result: false},
      %{answer: 1500, result: false},
      %{answer: 1492, result: true},
    ]
  }
]

我想使用Enum.shuffle对3个测验结构进行混洗,并对每个结构的答案列表进行混洗。我可以重新整理列表,但正在努力为每个结构更新答案列表。我该怎么办?

3 个答案:

答案 0 :(得分:4)

您可以重新整理列表,然后在其上进行映射,将每个answers字段替换为重新整理的版本

Enum.shuffle(list_of_quizzes)
|> Enum.map(fn(%{answers: answers} = quizz) -> 
    %{quizz | answers: Enum.shuffle(answers)}
end)

答案 1 :(得分:2)

我会接受Kernel.SpecialForms.for/1的理解:

for quizz <- Enum.shuffle(quizzes),
  do: %Quizz{quizz | answers: Enum.shuffle(quizz.answers)}

或者相反:

for quizz <- Enum.shuffle(quizzes),
    answers = Enum.shuffle(quizz.answers),
  do: %Quizz{quizz | answers: answers}

答案 2 :(得分:1)

您也可以使用Map.update!/3Kernel.update_in/3

quiz_list
|> Enum.shuffle
|> Enum.map(fn q -> Map.update!(q, :answers, &Enum.shuffle/1) end)