我有一个阵列,说:
products = [['product_1','description 1'],['product_2','description 2']]
我想根据键检查输入,例如:
product = raw_input('Enter product: ')
if product not in products.keys():
log.fatal('Invalid product: {}'.format(product))
exit(1)
keys()
不起作用 - 我该怎么办?
答案 0 :(得分:2)
列出没有键......你只想要每个子列表的第一个元素
getElementById()
或
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
答案 1 :(得分:2)
keys
不是list
的方法。你必须考虑dict
。只是做:
products = {k: v for k, v in [['product_1','description 1'],['product_2','description 2']]}