2015-02-11 160 views
0

我想动态分配一个变量,具体取决于我当前在列表中迭代的值。我想弄清楚如何做到这一点,我目前正在尝试使用exec()。我们的目标是自动迭代来自不同Twitter列表的推文,并将它们存储在以twitter列表名称命名的单独集合中,我将其中的一些代码留给流程的进一步上下文。在Python for循环中从列表中分配多个变量

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 

我怎么能解决这个问题,最好了解为什么出现这种情况?

+2

而不是使用“动态赋值”,只需使用Python内置方法'getattr'。例如:'current_collection = getattr(db,slug)'。 – noahbkim 2015-02-11 22:44:07

+0

那么,这解决了这个问题,我想我可以阅读文档中的getattr()来理解为什么这是一个更好的方法。 :-) – mattiasostmar 2015-02-11 22:50:19

+1

简单地说,'getattr'只是调用对象'__getattr__'的魔术方法。这意味着'getattr(db,slug)'几乎和'db.slug'完全一样。 – noahbkim 2015-02-11 23:16:33

回答

0

使用gettattr()而不是使用评论者建议的