我经常发现自己处于一种我想要迭代的逻辑连接符号组的情况。显而易见的解决方案是将这些符号添加到列表中,但是重复是一个需要维护的痛苦,我必须相信,如果我的同伴改变一个,他们也会改变另一个。Python:遍历一组符号
有没有办法在创建符号的同时将它们的值添加到列表中?
例如
# A group of like symbols that can be used independently in this scope
hippo = 'hippo'
gator = 'gator'
mouse = 'mouse'
# To loop across them I have to put them into a list
valid_animals = [hippo, gator, mouse] # Maintain me separately, fool!
伪代码,我想
# Data structure that declares symbols whose values can be iterated over
valid_animals = { # Even your mom could maintain this
hippo = 'hippo'
gator = 'gator'
mouse = 'mouse'
}
# Use the symbols by themselves
print "I had a", mouse, "in my house"
# Iterate over the symbols
print mouse in valid_animals # True
[Enum](https://docs.python.org/3/library/enum.html)是否适合您的需求? – rkersh
枚举很棒,但有微妙但显着的差异。最值得注意的是,枚举集中在符号的名称上,而不是符号的值。迭代时这特别明显。例如,如果我将'valid_animals'更改为Enum,'valid_animals中的print mouse'将返回False。 – user2859458
它可能不是你想要的,但是你可以在[i.value for i in valid_animals]中打印鼠标,对吧?而且,您可以添加一个'values'类方法,使其更漂亮一些(例如,在valid_animals.values()中打印鼠标)。 – rkersh