generating unique variable name via loops

Denis McMahon denismfmcmahon at gmail.com
Tue Nov 4 18:14:26 CET 2014


On Tue, 04 Nov 2014 05:45:04 -0800, Fatih Güven wrote:

> 4 Kasım 2014 Salı 15:19:20 UTC+2 tarihinde Veek M yazdı:
>> Fatih Güven wrote:
>> 
>> > 4 Kas?m 2014 Sal? 13:29:34 UTC+2 tarihinde Fatih Güven yazd?:
>> >> I want to generate a unique variable name for list using python.
>> >> 
>> >> list1=...
>> >> list2=...
>> 
>> for x in range(1,10):
>>     exec("list%d = []" % x)
> 
> This is okay but i can't use the method ".append" for example
> list1.append("abc")

This is one solution using a dictionary of lists to maintain the name 
association. It may not be the best method. It may not be the best 
solution for you. It may not be the answer your instructor is looking 
for, and it contains deliberate syntax errors.

lists = {}

for fn in filenames
    infile = open(fn, "r")
    lists[fn] = []
    for line in infile
        lists[fn].append(line)
    infile.close()

If you have to ask how to do this sort of thing, you probably shouldn't 
be coding employee data processing systems anyway!

If this was a coding assignment for a course, you should have had 
sufficient instruction in the relevant algorithms and language features 
to be able to figure it out yourself.

In either case, what not explain what you tried, what you expected it to 
do, and what it actually did.


-- 
Denis McMahon, denismfmcmahon at gmail.com



More information about the Python-list mailing list