These are ordered by closeness to the original attempt - I think something like the third approach is the most natural to work with.
Approach 1
This approach is the closest to the original in terms of how n
can be used, but is not very pretty otherwise...
Do[
Export[
"path" <> (Hold@n /. OwnValues@n /. Hold[x_] :> ToString[Unevaluated@x]) <> ".jpg",
ListPlot[n],
"JPEG"
],
{n, Unevaluated /@ Unevaluated@{lista, listb, listc}}
]
This relies on preventing evaluation of lista
,... at two key points:
- In the iterator specification of
Do
: Here, we need to wrap every element of the list in Unevaluated
. The second Unevaluated
is to prevent the list from being evaluated by Map
(the Unevaluated/@…
part)
- In the
ToString
part: We need to evaluate one layer of definitions (i.e. we need to insert the value of n
) using Hold[n]/.OwnValues[n]
. This gives us something of the form Hold[lista]
. Then we pass this to ToString
, where we use Unevaluated
again. Also, we do this using a replacement rule to have better control over the evaluation.
Approach 2
The main idea is similar, but we initially wrap the variables in Hold
to make handling them easier:
Do[
Export[
"path" <> (n /. Hold[x_] :> ToString[Unevaluated@x]) <> ".jpg",
ListPlot[ReleaseHold@n],
"JPEG"
],
{n, Hold /@ Unevaluated@{lista, listb, listc}}
]
As mentioned above, the main idea is similar to approach 1. The difference is that n
is now of the form Hold[lista]
. This means that we do not have to be so careful when getting the name of the symbol. We just have to use ReleaseHold
whenever we actually need to insert the value.
Approach 3
There are better ways to label data than to try and extract variable names (while simultaneously preventing their evaluation): Association
s. Most operations are transparent to the keys, but if you need them (e.g. to build the file name), you can access them using functions like KeyValueMap
:
lists = <|
"lista" -> {{1, 2}, {3, 4}, {3, 5}, {4, 8}},
"listb" -> {{3, 5}, {7, 6}, {2, 9}, {3, 7}},
"listc" -> {{1, 23}, {3, 23}, {34, 56}}
|>;
KeyValueMap[
Export["path" <> # <> ".jpg", ListPlot[#2], "JPEG"] &,
lists
]