在Python中的for循环中从列表中分配多个变量

时间:2015-02-11 22:17:14

标签: mongodb python-3.x twitter

我想根据我当前在列表中迭代的值动态分配变量。我正在试图弄清楚如何做到这一点,我正在尝试使用exec()。目的是自动迭代来自不同推特列表的推文,并将它们存储在以推文列表名称命名的单独集合中,我留下一些代码用于流程的进一步上下文。

slug_list = ["slug1","slug2","slug3"]

for slug in slug_list:
        exec("current_collection = db.{}".format(slug))

        tweets = api.list_timeline("@username",slug)
        for tweet in tweets_cursor:
            current_collection.insert(tweet)

这会产生以下错误:

NameError: name 'current_collection' is not defined

我怎么能解决这个问题,最好先了解为什么会这样?

1 个答案:

答案 0 :(得分:0)

使用gettattr()代替评论者建议