Problem with List of List

Paul Rubin http
Sat Aug 26 02:58:56 EDT 2006


"Kirt" <moqtar at gmail.com> writes:
> Actually here in my code  ['1', 'a', '6'], ['1', 'b', '6'], ['1', 'c',
> '6'] means:
>   1==> Directory name;
>   a,b,c,d=== Filename
>   6 ==> modified time
> 
> So i want the out put like:
>   Directory name: 1
>   Filename:a
>   modified time:6

Try writing the code in a style with fewer side effects.  I like using
itertools.groupby for this type of thing (not exactly tested):

    from itertools import groupby

    List=[['1', 'a', '6'], ['1', 'b', '6'], ['1', 'c', '6'],
          ['1', 'd', '6'],['2', 'a','6'], ['2', 'b', '6'],
          ['2', 'c', '6'], ['2', 'd', '6'], ['3', 'a', '6'],
          ['3','b', '6'], ['4', 'a', '6'], ['4', 'b', '6']]

    # retrieve directory name from one of those tuples
    def directory_name(t):   return t[0]   

    for dirname,dir_contents in groupby(sorted(List), directory_name):
      print 'Directory name:, dirname
      for dname2,filename,modtime in dir_contents:
         print 'Filename:%s\nmodified time:%s'% (filename, modtime)

The output is:

    >>> ## working on region in file /usr/tmp/python-9013z7X...
    Directory name: 1
    Filename:a
    modified time:6
    Filename:b
    modified time:6
    Filename:c
    modified time:6
    Filename:d
    modified time:6
    Directory name: 2
    Filename:a
    modified time:6
    Filename:b
    modified time:6
    Filename:c
    modified time:6
    Filename:d
    modified time:6
    Directory name: 3
    Filename:a
    modified time:6
    Filename:b
    modified time:6
    Directory name: 4
    Filename:a
    modified time:6
    Filename:b
    modified time:6
    >>>

Is that what you wanted?



More information about the Python-list mailing list