我有一长串要定义的变量(~100)。定义如下:
provider = node.xpath("//provider/text()")[0]
language = node.xpath("//language/text()")[0]
subtype = node.xpath("//subtype/text()")[0]
etc...
我如何更简洁地定义它/ DRY,类似于
COLUMN_VARIABLES = ['provider', 'language','subtype']
for variable in COLUMN_VARIABLES:
variable = node.xpath("//%s/text()"%variable)[0]
答案 0 :(得分:6)
更简洁的方法是使用字典:
COLUMN_VARIABLES = ['provider', 'language','subtype']
data = {}
for variable in COLUMN_VARIABLES:
data[variable] = node.xpath("//%s/text()"%variable)[0]
专业提示:每当你发现自己想要使用变量变量名时,就意味着你不需要变量,你希望一个容器代替所有数据。
答案 1 :(得分:3)
使用词典:
COLUMN_VARIABLES = ['provider', 'language','subtype']
vars = {}
for variable in COLUMN_VARIABLES:
vars[variable] = node.xpath("//%s/text()"%variable)[0]
答案 2 :(得分:1)
使用dict
保存结果:
column_vars = ['provider', 'language','subtype']
nodes = {}
for var in column_vars:
nodes[var] = node.xpath("//%s/text()" % variable)[0]