如何访问第二个列表(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...
答案 0 :(得分: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...
通过将颜色放入dict中,我们可以更轻松地检索它们并迭代它们的值。
如果你真的想从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...