【问题标题】:python how to search in multidimensional array / listpython如何在多维数组/列表中搜索
【发布时间】:2015-05-13 20:15:18
【问题描述】:

我无法弄清楚如何在以下列表/数组中搜索(存储在 self._map_commodities 中),并且数据是从 JSON 中获取的。

问题: 我想在数组中定位“wood”并返回与之相关的“size”值

我曾尝试使用 index(),但我无法让它工作。 T

class MyClass1(object):

    def __init__(self):
        self._data = ''
        self.list_commodities = []
        self._map_commodities = []

    def create_commodity_market(self):
        for commodity in self._data['commodities']:
            self.list_commodities.append(commodity['id'])
            self._map_commodities.append(commodity)

    def from_json(self):
        import json
        self._data = json.loads('{"commodities":[{"id":"food","size":"1.0"},{"id":"wood","size":"1.0"},{"id":"ore","size":"1.0"},{"id":"metal","size":"1.0"},{"id":"tools","size":"1.0"}]}')


x = MyClass1()
x.from_json()
x.create_commodity_market()
print(x.list_commodities)
print(x._map_commodities)
####print(x._map_commodities.index("wood")) # I want it to print the size-value of the wood object

提前谢谢你。

【问题讨论】:

  • 这个脚本返回什么输出?
  • 您需要向我们提供_map_commodities方法
  • ['food', 'wood', 'ore', 'metal', 'tools'] [{'id': 'food', 'size': '1.0'}, {' id': 'wood', 'size': '1.0'}, {'id': 'ore', 'size': '1.0'}, {'id': 'metal', 'size': '1.0' }, {'id': 'tools', 'size': '1.0'}] 我需要一种方法来搜索/匹配 id(食物、木材、矿石、金属、工具)并返回与它们相关的“大小”。我知道每个人都有 size: 1.0 但他们可能会有所不同。

标签: python arrays list search multidimensional-array


【解决方案1】:

基本上你想要的是:

print next(y['size'] for y in x._map_commodities if y['id'] == 'wood')

如果您的所有物品都没有 id 'wood',这将引发 StopIteration 异常。

更一般地,将这样的方法添加到MyClass1

def size_from_id(self, id_name):
    try:
        return next(y['size'] for y in self._map_commodities if y['id'] == id_name)
    except StopIteration:
        return None

那你可以拨打x.size_from_id('wood')

【讨论】:

    【解决方案2】:

    字典更适合你想要做的事情:

    class MyClass1(object):
    
    def __init__(self):
        self._data = ''
        self._map_commodities = {}
    
    def create_commodity_market(self):
        for commodity in self._data['commodities']:
            self._map_commodities[commodity['id']] = commodity['size']
    
    def from_json(self):
        import json
        self._data = json.loads('{"commodities":[{"id":"food","size":"1.0"},{"id":"wood","size":"1.0"},{"id":"ore","size":"1.0"},{"id":"metal","size":"1.0"},{"id":"tools","size":"1.0"}]}')
    
    
    x = MyClass1()
    x.from_json()
    x.create_commodity_market()
    print(x._map_commodities["wood"])
    

    【讨论】:

      【解决方案3】:

      您可以使用pandas 来处理数据

      import json
      import pandas as pd
      
      data = json.loads('{"commodities":[{"id":"food","size":"1.0"},{"id":"wood","size":"1.0"},{"id":"ore","size":"1.0"},{"id":"metal","size":"1.0"},{"id":"tools","size":"1.0"}]}')
      df = pd.DataFrame.from_dict(data['commodities'])
      
      # get the size of the row with id = 'wood'
      size = df[df['id'] == 'wood']['size']
      print size
      
      # you can get the value alone, too
      print size.values[0]
      

      【讨论】:

        【解决方案4】:

        首先,您需要返回函数的具体值:

        def from_json(self):
                import json
                self._data = json.loads('{"commodities":[{"id":"food","size":"1.0"},{"id":"wood","size":"1.0"},{"id":"ore","size":"1.0"},{"id":"metal","size":"1.0"},{"id":"tools","size":"1.0"}]}')
                return self._data
        

        然后使用索引获取一个单词的相关size。例如:

        x = MyClass1()
        d=x.from_json()
        print d['commodities'][1]['size']
        u'1.0'
        

        【讨论】:

        • “return elf._data”应该是“return self._data”
        猜你喜欢
        • 2020-07-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多