[Tutor] List's name in a string

"Héctor Villafuerte D." hec.villafuerte at telgua.com.gt
Tue Sep 30 12:50:28 EDT 2003


Jeff Shannon wrote:

> You can sortof force it by going through locals() and globals(), but a 
> better approach would probably be to look again at *why* you want this.
>
> Most of the time, if you need to refer to some variable name 
> programmatically like this, what you're really looking for is a list 
> or a dictionary.  In other words, you typically want to refer to 
> variables by a variable name so that you can select one object from a 
> set of possible objects based on some runtime parameter.  That's 
> exactly the niche that dictionaries fit.  For example,
>
> >>> data = {}
> >>> data['list1'] = [1, 2, 3]
> >>> data['list2'] = [4, 5, 6]
> >>> data
> {'list1': [1, 2, 3], 'list2': [4, 5, 6]}
> >>> key = 'list1'
> >>> data[key]
> [1, 2, 3]
> >>>
>
> Maybe if you explain a bit more about your intent, we can explore an 
> easier way to accomplish your goal than mucking about in the 
> interpreter's innards.


You're right, I need to briefly explain what I want to do:
* There's a list (LIST) which contains filenames (as strings); i.e.: 
LIST = ['file1', 'file2'].
* There's some processing on each file refered to by LIST.
* The processed output should be stored in a file named 'LIST_proc' 
(producing just one
output file, appending the results from 'file1', 'file2', etc.)

Thanks.




More information about the Tutor mailing list