【问题标题】:How to iterate over keys in array of arrays?如何遍历数组数组中的键?
【发布时间】:2016-06-23 19:59:03
【问题描述】:

我有一个数组,比如说:

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() 不起作用——我该怎么办?

【问题讨论】:

    标签: python arrays python-2.7


    【解决方案1】:

    列表没有键...您只需要每个子列表的第一个元素

    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']]}
      

      【讨论】:

      • 或者直接在你的名单上打电话给dict...很好的答案都一样
      猜你喜欢
      • 2022-01-21
      • 1970-01-01
      • 2011-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-09
      相关资源
      最近更新 更多