#1
  1. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    606
    Rep Power
    65

    'namedtuple' question


    I fooled around with 'namedtuples' and promptly got into troubles:
    Code:
    from collections import namedtuple
    
    # a test list of (name, age, weight) tuples
    data_list = [
    ('Sarah Gellar', 26, 121),
    ('Alec Baldwin', 47, 214),
    ('Mandy Moore', 22, 135),
    ('Matthew Goode', 29, 167),
    ('Amanda Bynes', 19, 112),
    ('James Kirk', 24, 175)
    ]
    
    # create a list of instances
    star_list = [namedtuple('movie_star', 'name age weight') \
                 for name, age, weight in data_list]
    
    #print(star_list)
    
    print(star_list[1])
    
    print(star_list[1]._fields)
    
    print(star_list[1].name)
    print(star_list[2].name)
    
    ''' now I am stuck, how to get the name? >>>
    <class '__main__.movie_star'>
    ('name', 'age', 'weight')
    <property object at 0x02A8E9C0>
    <property object at 0x02A8EBA0>
    '''
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2007
    Location
    Joensuu, Finland
    Posts
    430
    Rep Power
    66
    Originally Posted by Dietrich
    I fooled around with 'namedtuples' and promptly got into troubles:
    Yep. namedtuple() should be used to create a new type, not a new instance.

    First create a named tuple with the fields you require, then use your data to occupy a list of these kinds of tuples, as in:

    Code:
    >>> from collections import namedtuple
    >>> Star = namedtuple('Star', ['name', 'age', 'weight'])
    >>> data_list = [
    ('Sarah Gellar', 26, 121),
    ('Alec Baldwin', 47, 214),
    ('Mandy Moore', 22, 135),
    ('Matthew Goode', 29, 167),
    ('Amanda Bynes', 19, 112),
    ('James Kirk', 24, 175)
    ]
    >>> movie_stars = [Star(name=name, age=age, weight=weight) for name, age, weight in data_list]
    >>> 
    >>> movie_stars
    [Star(name='Sarah Gellar', age=26, weight=121), Star(name='Alec Baldwin', age=47, weight=214), Star(name='Mandy Moore', age=22, weight=135), Star(name='Matthew Goode', age=29, weight=167), Star(name='Amanda Bynes', age=19, weight=112), Star(name='James Kirk', age=24, weight=175)]
    >>> movie_stars[1].name
    'Alec Baldwin'
    My armada: openSUSE 13.1 (home desktop, home laptop), Crunchbang Linux 11 (mini laptop, work laptop), Android 4.2.1 (tablet)
  4. #3
  5. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    606
    Rep Power
    65
    Thanks SuperOscar, you defected my mistake!
    Now it works just fine!
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25

IMN logo majestic logo threadwatch logo seochat tools logo