任何方式从字符串值中提取变量名称?
我有三个列表。根据用户的交互,这些列表可能对用户可用或不可用,我设置的方式是通过第四个列表跟踪列表名称和状态。但是当我尝试使用我的第四个列表中的字符串值来访问我的其他列表时,我遇到了麻烦。任何方式从字符串值中提取变量名称?
也就是说,我想将可用列表中的所有字符串添加到主列表中 - 我应该如何处理这个问题?
domesticated = ['cow', 'sheep', 'pig']
pets = ['cat', 'dog']
wildlife = ['giraffe', 'lion', 'panda']
masterList = ['domesticated', 'pets', 'wildlife'], ['off', 'on', 'on']
def currentLists():
activeList = ''
for i in range(len(masterList[0])):
if masterList[1][i] == 'on':
activeList = activeList + masterList[0][i]
return activeList
电流输出:
petswildlife
所需的输出:
['cat', 'dog', 'giraffe', 'lion', 'panda']
我带来的困惑表示歉意,我与Python一个完整的初学者。任何援助非常感谢。
你不应该使用字符串,而是变量本身。我还将脚本更改为使用zip
:zip([1, 2, 3], [4, 5, 6]) == [(1, 4), (2, 5), (3, 6)]
。你......用它压缩序列。
domesticated = ['cow', 'sheep', 'pig']
pets = ['cat', 'dog']
wildlife = ['giraffe', 'lion', 'panda']
masterList = zip([domesticated, pets, wildlife], ['off', 'on', 'on'])
def currentLists():
activeList = []
for e in masterList:
if e[1] == 'on':
activeList += e[0]
return activeList
解决了它,谢谢!我会在zip上阅读。 – ZincAddendum 2012-02-26 14:05:57
你应该用一个单一的dict
更换三个变量domesticated
,pets
和wildlife
:
animals = {'domesticated': ['cow', 'sheep', 'pig'],
'pets': ['cat', 'dog'],
'wildlife': ['giraffe', 'lion', 'panda']}
然后
activeList = [] # not ''!
for category, status in zip(*masterList):
if status == 'on':
activeList += animals[category]
注意zip(*masterList)
,这意味着相同的zip(masterList[0], masterList[1])
。使用zip
和两个循环变量是同时循环两个列表的惯用方式。
对于额外的Python的点,你可以使用sum
追加名单:
sum((animals[category] for category, status in zip(*masterList)
if status == 'on'),
[])
尽管Gandaro's good advice,通过名称检索变量可能。
有vars(),globals()和locals()的功能。 所以,如果你想直接修复它,你能做到这一点是这样的:
domesticated = ['cow', 'sheep', 'pig']
pets = ['cat', 'dog']
wildlife = ['giraffe', 'lion', 'panda']
masterList = ['domesticated', 'pets', 'wildlife'], ['off', 'on', 'on']
def currentLists():
activeList = []
for i in range(len(masterList[0])):
if masterList[1][i] == 'on':
activeList = activeList + globals()[masterList[0][i]]
return activeList
我不会推荐使用'vars','globals'或'locals'给新手程序员。 – 2012-02-26 15:15:04
使用像动物的字典= {“宠物”:“猫”,“DOC”]};动物[“宠物”。忘记使用全局变量()和本地变量()。 – BatchyX 2012-02-26 13:53:48