[英]How to iterate over keys in array of arrays?
I have an array, say: 我有一个数组,说:
products = [['product_1','description 1'],['product_2','description 2']]
And I want to check input against the keys, eg,: 我想根据按键检查输入,例如:
product = raw_input('Enter product: ')
if product not in products.keys():
log.fatal('Invalid product: {}'.format(product))
exit(1)
keys()
doesn't work -- what should I be doing? keys()
不起作用-我应该怎么办?
lists dont have keys ... you just want the first element of each sublist 列表没有键...您只想要每个子列表的第一个元素
dict(products).keys() #ONLY if there is exactly 2 items per sublist
or 要么
zip(*products)[0] #any number of items per sublist is ok
or 要么
[k for k,val in products] # only if you have EXACTLY 2 items per sublist
or 要么
[item[0] for item in products] # any number of items in each sublist
keys
is not a method of a list
. keys
不是list
的方法。 You must be thinking of a dict
. 你一定在想一本
dict
。 Just do: 做就是了:
products = {k: v for k, v in [['product_1','description 1'],['product_2','description 2']]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.