0

如何访问我的第二个列表 (val) 中的值?

colors = [('teal','30a8a0'),('pink','b33b96'),('red','de3249'),('green','758f3d'),('purple','532c86'),('darkblue','116da4'),('skyblue','1d9dc5')]
darkblue=[('first'),('second')]

for (color,value) in colors:
    print color #teal, pink, red, etc...
    for (val) in {color}:
        print val #first, second, etc...
4

1 回答 1

3

这个怎么样?

subcolors = {'darkblue': ['first', 'second'],
             'teal': ['first-teal', 'second-teal'],
             'pink': ['first-pink', 'second-pink'],
             # etc..
            }

for (color,value) in colors:
    print color #teal, pink, red, etc...
    for val in subcolors[color]:
        print val #first-teal, second-teal, first-pink, second-pink, etc...

通过将颜色放入字典中,我们可以更轻松地检索它们并遍历它们的值。


如果您真的想从darkblue变量中执行此操作并且您不想使用 dict,您可以这样做,但我不推荐它:

darkblue = ['first', 'second']
teal = ['first-teal', 'second-teal']
pink = ['first-pink', 'second-pink']
# etc...

for (color,value) in colors:
    print color #teal, pink, red, etc...
    for val in locals()[color]:
        print val #first-teal, second-teal, first-pink, second-pink, etc...
于 2012-04-12T21:08:02.963 回答