What are some easy ways to convert a List of Rules
{"Joe" -> 94, "Jane" -> 85, "Bob" -> 82, "Bill" -> 83, "Michelle" -> 98}
into a List of Lists
{{Joe, 94}, {Jane, 85}, {Bob, 82}, {Bill, 83}, {Michelle, 98}}
?
What are some easy ways to convert a List of Rules
{"Joe" -> 94, "Jane" -> 85, "Bob" -> 82, "Bill" -> 83, "Michelle" -> 98}
into a List of Lists
{{Joe, 94}, {Jane, 85}, {Bob, 82}, {Bill, 83}, {Michelle, 98}}
?
list = {"Joe" -> 94, "Jane" -> 85, "Bob" -> 82, "Bill" -> 83, "Michelle" -> 98};
List @@@ list
{{"Joe", 94}, {"Jane", 85}, {"Bob", 82}, {"Bill", 83}, {"Michelle",
98}}
which is a short notation, thanks @ Alexey Popkov, for
Apply[List, list, {1}]
Or
list /. Rule :> List
Or
Extract[#, {{1}, {2}}] & /@ list
Apply[List,list,2] be Apply[List,list,1]. I took your example, went to the documentation, and found: The short form @@@ is equivalent to applying at level 1. Next, I tried FullForm[list] and your suggestion list/.Rule:>List made immediate sense, but list/.Rule->List also worked. Thanks for some great answers. Still working on the last one.
– David
Nov 28 '15 at 18:41
List @@@ list is equivalent to Apply[List, list, {1}] as you can immediately see from List @@@ list // Hold // InputForm.
– Alexey Popkov
Nov 28 '15 at 23:03
for something different, for any list of rules e.g.
list = {"Joe" -> 94, "Jane" -> 85, "Bob" -> 82, "Bill" -> 83, "Michelle" -> 98}
then
list[[All, 0]] = List;list
will return what you want
data = {"Joe" -> 94, "Jane" -> 85, "Bob" -> 82, "Bill" -> 83, "Michelle" -> 98};
As Eldo points out
List @@@ data
is most likely the best way to do this. But a destructing function would be fairly competitive. It also provides a direct visual representation of the operation sought, which makes it easy to come to mind.
f[k_ -> v_] := {k, v}
f /@ data
Starting with V10, there are two new ways to this.
Apply[List] /@ data
and
Association[data] // KeyValueMap[List]
The last is a little kinky though.
data/.(k_->v_)->{k,v}. And the last kinky one gives me an introduction to moving back and forth from associations to lists. Thanks. Nice answer.
– David
Nov 28 '15 at 19:01
Association[data] may lead to a large overhead. That is, once an Association object is in memory, performing operations on it may be fast, but constructing the Association might be quite slow.
– LLlAMnYP
Nov 29 '15 at 13:28
<| key -> val,...|> into {{key,val},...}. KeyValueMap is more than 50% faster than something like List@@@(Normal@assoc).
– bobthechemist
Mar 20 '16 at 13:29
l= {"Joe" -> 94, "Jane" -> 85, "Bob" -> 82, "Bill" -> 83,
"Michelle" -> 98};
Transpose[{l[[;; , 1]], l[[;; , 2]]}]
{"Joe" -> 94, "Jane" -> 85, "Bob" -> 82, "Bill" -> 83,
"Michelle" -> 98} //. {a___, Rule[s_ , f_], g___} :> {a, {s, f}, g}
=> {{"Joe", 94}, {"Jane", 85}, {"Bob", 82}, {"Bill", 83}, {"Michelle",
98}}