A question on the creation of list of lists

alex23 wuwei23 at gmail.com
Tue Apr 28 08:42:15 CEST 2015


On 23/04/2015 2:18 AM, subhabrata.banerji at gmail.com wrote:
> I have a list of file names of a directory, I want to read each one of them.
> After reading each one of them, I want to put the results of each file in a list.
> These lists would again be inserted to create a list of lists.

While there's nothing wrong with for loops, Python does provide list 
comprehensions which can help simplify list creation.

If you just want a list with each element being a list of the contents 
of a file:

     all_content = [ open(x, 'r').readlines() for x in list_of_files ]

If you want a list containing a list of filenames and another list 
holding the content lists (which you seem to be wanting from your code):

     files_and_content = zip(list_of_files, all_content)

Another useful way of storing data such as this is in a dictionary, 
using the filenames as keys:

    file_content = { x:open(x, 'r').readlines() for x in list_of_files }

What structure is most important is, of course, dependent on what you 
want to do with it next.



More information about the Python-list mailing list