开发者

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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜