Python: Expanding List of Class Objects
this is a quick one. Suppose I got a multidimensional list of class objects, named tab开发者_StackOverflow中文版le
, 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.
{arg_name.attribute_name} also works:
for row in table:
print(' - '.join('{0.name}'.format(elt) for elt in row))
Like this, for example:
for row in table:
print '{0} - {1} - {2}'.format(*[x.name for x in row])
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?
精彩评论