python如何在多维数组/列表中搜索

时间:2015-03-11 20:34:44

标签: python arrays list search multidimensional-array

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

问题: 我想找到" wood"在数组中返回" size"与之相关的价值

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

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

提前谢谢。

4 个答案:

答案 0 :(得分: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')

答案 1 :(得分:0)

首先,您需要返回函数的特定值:

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'

答案 2 :(得分:0)

您可以使用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]

答案 3 :(得分:0)

字典更适合您尝试做的事情:

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"])