What are some easy ways to convert a List
of Rule
s
{"Joe" -> 94, "Jane" -> 85, "Bob" -> 82, "Bill" -> 83, "Michelle" -> 98}
into a List
of List
s
{{Joe, 94}, {Jane, 85}, {Bob, 82}, {Bill, 83}, {Michelle, 98}}
?
What are some easy ways to convert a List
of Rule
s
{"Joe" -> 94, "Jane" -> 85, "Bob" -> 82, "Bill" -> 83, "Michelle" -> 98}
into a List
of List
s
{{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.
$\endgroup$
List @@@ list
is equivalent to Apply[List, list, {1}]
as you can immediately see from List @@@ list // Hold // InputForm
.
$\endgroup$
Nov 28, 2015 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.
$\endgroup$
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.
$\endgroup$
<| key -> val,...|>
into {{key,val},...}
. KeyValueMap
is more than 50% faster than something like List@@@(Normal@assoc)
.
$\endgroup$
Mar 20, 2016 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}}