Getting ID field while using for cycle with objects
what is the best way to get for
number each time it run开发者_如何学JAVAs?
Code:
fields = []
objects = otherobjects.all()
for object in objects
fields.append(('id_is_#', object))
I want to put an ID to # place. ID would be generated ++ way.
fields = []
objects = otherobjects.all()
for id, obj in enumerate(objects)
fields.append(('id_is_' + id, obj))
List comprehension:
objects = otherobjects.all()
fields = [('id_is_%d' % id, ob) for id, ob in enumerate(objects)]
Using 'object' as a variable name could cause problems...
String modulation is better for this.
fields.append(("id_is_%s" % id, object))
Edit: Slight correction on the style just in case you mean something slightly differently here is a better example
for obj in objects:
fields.append(("id_is_%s" % obj.id, obj)
精彩评论