如何在Python中处理2D数组?

如何在Python中处理2D数组?,python,python-2.7,multidimensional-array,Python,Python 2.7,Multidimensional Array,我想要一个2D数组,第一个参数是学生的名字,第二个是他的结果 我试试这个: listStudentResult = [] listStudentResult.append([]) listStudentResult[0].append("Alex") listOfasinEan[0].append(20) lisStudentResult.append([]) listStudentResult[1].append(Paul) listStudentResult[1].append(15)

我想要一个2D数组,第一个参数是学生的名字,第二个是他的结果

我试试这个:

listStudentResult = [] 
listStudentResult.append([])
listStudentResult[0].append("Alex")
listOfasinEan[0].append(20)

lisStudentResult.append([])
listStudentResult[1].append(Paul)
listStudentResult[1].append(15)
我怎么知道亚历克斯的结果? 我不想要
listStudentResult[0][1]
我需要像这样的东西

listStudentResult[0]["Alex"]
使用字典:

listStudentResult = [] 
listStudentResult.append({"Alex": 20})
listStudentResult.append({"Paul": 15})
使用字典:

listStudentResult = [] 
listStudentResult.append({"Alex": 20})
listStudentResult.append({"Paul": 15})

通过查看您的需求,我建议您使用python中的字典

为了解释这本词典,我将以你为例

listStudentResult = dict()
listStudentResult['Alex'] = 20
listStudentResult['Paul'] = 15

您可以使用listStudentResult['Alex']访问元素。

通过查看您的需求,我建议您使用python中的字典

为了解释这本词典,我将以你为例

listStudentResult = dict()
listStudentResult['Alex'] = 20
listStudentResult['Paul'] = 15
您可以使用listStudentResult['Alex']访问元素。

复杂类:

class AutoVivification(dict):
    """Implementation of perl's autovivification feature. Has features from both dicts and lists,
    dynamically generates new subitems as needed, and allows for working (somewhat) as a basic type.
    """
    def __getitem__(self, item):
        if isinstance(item, slice):
            d = AutoVivification()
            items = sorted(self.iteritems(), reverse=True)
            k,v = items.pop(0)
            while 1:
                if (item.start < k < item.stop):
                    d[k] = v
                elif k > item.stop:
                    break
                if item.step:
                    for x in range(item.step):
                        k,v = items.pop(0)
                else:
                    k,v = items.pop(0)
            return d
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value

    def __add__(self, other):
        """If attempting addition, use our length as the 'value'."""
        return len(self) + other

    def __radd__(self, other):
        """If the other type does not support addition with us, this addition method will be tried."""
        return len(self) + other

    def append(self, item):
        """Add the item to the dict, giving it a higher integer key than any currently in use."""
        largestKey = sorted(self.keys())[-1]
        if isinstance(largestKey, str):
            self.__setitem__(0, item)
        elif isinstance(largestKey, int):
            self.__setitem__(largestKey+1, item)

    def count(self, item):
        """Count the number of keys with the specified item."""
        return sum([1 for x in self.items() if x == item])

    def __eq__(self, other):
        """od.__eq__(y) <==> od==y. Comparison to another AV is order-sensitive
        while comparison to a regular mapping is order-insensitive. """
        if isinstance(other, AutoVivification):
            return len(self)==len(other) and self.items() == other.items()
        return dict.__eq__(self, other)

    def __ne__(self, other):
        """od.__ne__(y) <==> od!=y"""
        return not self == other
示例:

d = vividict()
print d

d['John']['results'] = [90]

print d

d['John']['results'].append(10) 

print d     

d = AutoVivification()

print d

d['John']['results'][0]=20
print d
d['John']['results'].append(20)

for result in [30,25,60,100,99]:
    d['John']['results'].append(result)

onlyNumbers=True

lastKey=max(d['John']['results'].keys())
for n,result in enumerate('5 15 25 33.1 40'.split()):
    n+=lastKey
    d['John']['results'][n]=result if not onlyNumbers else float(result)

print d

from pprint import pprint as ppr

ppr(d)

'''
output:
{}
{'John': {'results': [90]}}
{'John': {'results': [90, 10]}}
{}
{'John': {'results': {0: 20}}}
{'John': {'results': {0: 20, 1: 20, 2: 30, 3: 25, 4: 60, 5: 100, 6: 5.0, 7: 15.0, 8: 25.0, 9: 33.1, 10: 40.0}}}
{'John': {'results': {0: 20,
                      1: 20,
                      2: 30,
                      3: 25,
                      4: 60,
                      5: 100,
                      6: 5.0,
                      7: 15.0,
                      8: 25.0,
                      9: 33.1,
                      10: 40.0}}}   


'''
复杂类:

class AutoVivification(dict):
    """Implementation of perl's autovivification feature. Has features from both dicts and lists,
    dynamically generates new subitems as needed, and allows for working (somewhat) as a basic type.
    """
    def __getitem__(self, item):
        if isinstance(item, slice):
            d = AutoVivification()
            items = sorted(self.iteritems(), reverse=True)
            k,v = items.pop(0)
            while 1:
                if (item.start < k < item.stop):
                    d[k] = v
                elif k > item.stop:
                    break
                if item.step:
                    for x in range(item.step):
                        k,v = items.pop(0)
                else:
                    k,v = items.pop(0)
            return d
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value

    def __add__(self, other):
        """If attempting addition, use our length as the 'value'."""
        return len(self) + other

    def __radd__(self, other):
        """If the other type does not support addition with us, this addition method will be tried."""
        return len(self) + other

    def append(self, item):
        """Add the item to the dict, giving it a higher integer key than any currently in use."""
        largestKey = sorted(self.keys())[-1]
        if isinstance(largestKey, str):
            self.__setitem__(0, item)
        elif isinstance(largestKey, int):
            self.__setitem__(largestKey+1, item)

    def count(self, item):
        """Count the number of keys with the specified item."""
        return sum([1 for x in self.items() if x == item])

    def __eq__(self, other):
        """od.__eq__(y) <==> od==y. Comparison to another AV is order-sensitive
        while comparison to a regular mapping is order-insensitive. """
        if isinstance(other, AutoVivification):
            return len(self)==len(other) and self.items() == other.items()
        return dict.__eq__(self, other)

    def __ne__(self, other):
        """od.__ne__(y) <==> od!=y"""
        return not self == other
示例:

d = vividict()
print d

d['John']['results'] = [90]

print d

d['John']['results'].append(10) 

print d     

d = AutoVivification()

print d

d['John']['results'][0]=20
print d
d['John']['results'].append(20)

for result in [30,25,60,100,99]:
    d['John']['results'].append(result)

onlyNumbers=True

lastKey=max(d['John']['results'].keys())
for n,result in enumerate('5 15 25 33.1 40'.split()):
    n+=lastKey
    d['John']['results'][n]=result if not onlyNumbers else float(result)

print d

from pprint import pprint as ppr

ppr(d)

'''
output:
{}
{'John': {'results': [90]}}
{'John': {'results': [90, 10]}}
{}
{'John': {'results': {0: 20}}}
{'John': {'results': {0: 20, 1: 20, 2: 30, 3: 25, 4: 60, 5: 100, 6: 5.0, 7: 15.0, 8: 25.0, 9: 33.1, 10: 40.0}}}
{'John': {'results': {0: 20,
                      1: 20,
                      2: 30,
                      3: 25,
                      4: 60,
                      5: 100,
                      6: 5.0,
                      7: 15.0,
                      8: 25.0,
                      9: 33.1,
                      10: 40.0}}}   


'''

您需要一个
list
dict
s。您需要一个
list
dict
s。