Python一次循环访问两个元素 [英] Python for loop access two elements at a time

查看:492
本文介绍了Python一次循环访问两个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  value + 

我在字典的值部分添加了一个名称和一个项目的属性值: = child.get('name')+'\ t'+ child.text +'\ t'

每个文本都由一个制表符分隔。所以,当我稍后处理这个值的字符串,我分裂在选项卡上,并有一个for循环遍历列表。



如何访问名称和值在for循环中。至于每个属性,我想一次性获取名称和值,并将其写入文件。目前这个列表看起来像:

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



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

解决方案

您可以遍历步长为2的列表,并获取每个迭代的名称和标记...

 对于范围(0,len(list1),2):
name = list1 [i]
tag = list1 [i + 1]
print'< tag name =%s>%s< / tag>'%(name,tag)


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 '>'

解决方案

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)

这篇关于Python一次循环访问两个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆