2016-06-03 4 views
0

Ich möchte ein 2D-Array haben, der erste Parameter ist der Name des Schülers und der zweite ist sein Ergebnis.Wie geht es mit 2D-Array in Python?

ich versuche dies:

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

lisStudentResult.append([]) 
listStudentResult[1].append(Paul) 
listStudentResult[1].append(15) 

Wie kann ich das Ergebnis von Alex haben? Ich will nicht listStudentResult[0][1] Ich brauche so etwas wie

listStudentResult[0]["Alex"] 
+1

Sie benötigen einen 'list' von' dict's. – Will

Antwort

2

Durch auf Ihre Anforderung suchen, würde ich vorschlagen, Sie Wörterbuch in Python zu verwenden.

Wörterbuch Um zu erklären, werde ich dein Beispiel nehmen

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

Sie die Elemente mit listStudentResult zugreifen kann [ 'Alex'].

2

Verwenden Wörterbücher:

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

Danke, es funktioniert auch – parik

1

Complex Klasse:

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 

Einfach Klasse:

class vividict(dict): 
    def __getitem__(self, item): 
     try: 
      return dict.__getitem__(self, item) 
     except KeyError: 
      value = self[item] = type(self)() 
      return value 

Beispiele:

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


'''