newbie question - python lists
Emily Rodgers
emily at nospam.com
Fri Nov 6 12:00:30 EST 2009
"lee" <san82moon at gmail.com> wrote in message
news:8d1009a4-54c8-4bb3-9862-8b22e6b42a3b at y10g2000prg.googlegroups.com...
> hi,
>
> rfids= ['01','02']
> i = 01
> row = {}
> items = []
> for rfid in rfids:
>
> brains = ['1','2']
>
> if brains:
> for brain in brains:
> # this loop must run only once for each value of i
> row['itemnos'] = 'item_0'+str(i)+'s'
> print 'hi'
> items.append(row)
> print items
> break
> i=i+1
>
> the above code produces output a:
> [{'itemnos': 'item_02s'}, {'itemnos': 'item_02s'}]
> but i want it to be,
> [{'itemnos': 'item_01s'}, {'itemnos': 'item_02s'}]
>
> can anyone point wer am erroring.
> Thanks in advance.
Hi,
As some others have pointed out, it is not totally clear from your code what
you are trying to do, but I will forgive you for that because you are
clearly not used to python!
I think what you are trying to do is:
items = []
rfids= ['01','02']
for rfid in rfids:
items.append({'itemnos': 'item_%ss' % rfid})
print items
This can also be done using a list comprehension which is one of the (many)
most useful features of python (imo):
rfids= ['01','02']
print [{'itemnos': 'item_%ss' % rfid} for rfid in rfids]
Or on one line (although it is always to be clearer rather trying to fit
stuff into one line - it is not perl!)
print [{'itemnos': 'item_%ss' % rfid} for rfid in ['01', '02']]
Hope this helps.
Emily
More information about the Python-list
mailing list