1

this is a quick one. Suppose I got a multidimensional list of class objects, named table, and I need to access the class attribute .name.

I don't want to use nested loops, and of course to print this, I need to use format().

for i in range(3):
    print '{0} - {1} - {2}'.format(*table[i].name)

Obviously that didn't work. As well as (*table[i]).name. I need to be able to access .name for each class object in the table[i] list. Mind if you put me to the right direction? Thanks in advance.

1
  • 1
    Why don't you want to use nested for loops? You'll have to loop through all the elements anyway. You're not saving yourself operations. Commented Dec 15, 2010 at 14:54

3 Answers 3

4

{arg_name.attribute_name} also works:

for row in table:
    print(' - '.join('{0.name}'.format(elt) for elt in row))
Sign up to request clarification or add additional context in comments.

Comments

1

Like this, for example:

for row in table:
    print '{0} - {1} - {2}'.format(*[x.name for x in row])

Comments

1

I don't want to use nested loops

This is silly. To iterate over each element of a multidimensional array, you need to use nested loops. They may be implicit (map or a list comprehension) but that doesn't mean they're not there! The following is going to be much neater and cleaner than anything with map or a nasty format unpacking.

for row in table:
    for elt in row:
        print <...>

If you really want to know how to use your method:

import operator
for row in table:
    print '{0} - {1} - {2}'.format(*map(operator.attrgetter('name'), row))

Tell me that's not messy and unclear compared to the above, not to mention the fact that you've hardcoded in the magic constant 3 -- what if you want to change to a 4x4 table?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.