for循环中的参数

时间:2018-06-14 09:41:42

标签: python python-3.x function for-loop arguments

请帮助我卡住

def printdata(something):
    for i in something + "_raw":
        something + "_raw_names" = i.findAll("div",{"itemprop":"name"})
        something + "_name" = something + "_raw_names"[0].text
        print("Name: " + something + "_name")

我希望printdata(body)这样做:

for i in bodies_raw:
    bodies_raw_names = i.findAll("div",{"itemprop":"name"})
    bodies_name = bodies_raw_names[0].text
    print("Name: " + bodies_name)

如果你有解决方案请告诉我因为我用这种方式挣扎太久了

1 个答案:

答案 0 :(得分:4)

您不应该尝试动态创建/访问/修改变量名称。如果您有许多类似命名的变量,请考虑将它们存储在dict中。例如:

raws = {'bodies': bodies_raw, 'other': other_raw}

然后你的功能可以是:

def printdata(something):
    for i in raws[something]:
        raw_names = i.findAll("div", {"itemprop": "name"})
        raw_name = raw_names[0].text
        print("Name: " + raw_name)