2016-06-23 56 views
1

我有一個數組,說:如何遍歷數組數組中的鍵?

products = [['product_1','description 1'],['product_2','description 2']] 

我要檢查輸入對鍵,e.g,:

product = raw_input('Enter product: ') 
if product not in products.keys(): 
    log.fatal('Invalid product: {}'.format(product)) 
    exit(1) 

keys()不工作 - 我應該怎樣做?

回答

2

名單不要有鑰匙......你只是希望每個子列表的第一個元素

dict(products).keys() #ONLY if there is exactly 2 items per sublist 

zip(*products)[0] #any number of items per sublist is ok 

[k for k,val in products] # only if you have EXACTLY 2 items per sublist 

[item[0] for item in products] # any number of items in each sublist 
2

keys不是list的方法。你一定在想着dict。只要做:

products = {k: v for k, v in [['product_1','description 1'],['product_2','description 2']]} 
+0

或只是直接在您的列表上調用'dict' ...好回答都一樣 –