Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python for loop access two elements at a time [duplicate]

I'm adding into the value section of a dictionary a name and the value of properties of an item:

value+=child.get('name') + '\t' + child.text + '\t' 

Each piece of text is separated by a tab. So then when I process this value string later, I split on the tabs and have a for loop to iterate over the list.

How can I access both the name and value in the for loop. As for each property I want to get the name and value in one go and write it to a file. Currently the list looks like:

[a,b,a,b,a,b,a,b]

and for each a,b I want to write:

'<' tag name=a '>' b '<' /tag '>'

like image 945
charlie123 Avatar asked Aug 01 '12 16:08

charlie123


2 Answers

You can iterate over the list with step size 2, and get the name and tag each over each iteration...

for i in range(0,len(list1),2):
    name = list1[i]
    tag = list1[i+1]
    print '<tag name="%s">%s</tag>' % (name, tag)
like image 177
jmetz Avatar answered Nov 02 '22 14:11

jmetz


Edit: If your keys are unique, and the ordering doesn't matter, then...

I think you should convert your list to a dictionary, and then iterate over the keys of the dictionary:

# assuming you converted your list to a dictionary called values

for k in values:
   print '<tag name="%s">%s</tag>' % (k, values[k])

Edit: If you don't need the dictionary for anything but printing out the result, then the other answer that was posted is probably a better method.

like image 4
Gordon Bailey Avatar answered Nov 02 '22 14:11

Gordon Bailey