Python:
bruk av datastrukturer

eksempel med Boston Marathon-data

data = {
    'name': [],
    'gender': [],
    'age': [],
    'division': [],
    'country': [],
    'time': []
}

Hva er dette?

L = []     # list

T = ()     # tuple

D = {}     # dictionary

S = set()     # set
L = [1, 2, 3]    # list

T = (1, 2, 3)    # tuple

D = {'a': 1, 'b': 2, 'c': 3}  # dict.

S = {1, 2, 3}    # set

dictionary med tomme lister som innhold

Boston Marathon - følgende eksempel er en bearbeidet versjon av kode fra kap. 17.1 i

Guttag, J,V, 2016: Introduction to computation and programming using Python

"Gebremariam Gebregziabher",M,27,14,ETH,142.93
"Matebo Levy",M,22,2,KEN,133.10
"Cherop Sharon",F,28,1,KEN,151.83
"Chebet Wilson",M,26,5,KEN,134.93
"Dado Firehiwot",F,28,4,ETH,154.93
"Korir Laban",M,26,6,KEN,135.48
"Jeptoo Rita",F,31,6,KEN,155.88
"Korir Wesley",M,29,1,KEN,132.67
"Kipyego Bernard",M,25,3,KEN,133.22
"Barmasai David",M,23,8,KEN,137.27

....

Nr. 21541
"Miller Casey A.",M,36,3530,USA,285.20
# 0. Name (string),
# 1. Gender (string)
# 2. Age (int)
# 3. Division (int),
# 4. Country (string),
# 5. Overall time (float) 

Text

Boston Marathon 2012

with open('bm_results2012.txt') as f:

    lines = f.readlines()
    
    for line in lines:
        split = line.split(',')
        data['name'].append(split[0])
        data['gender'].append(split[1])
        data['age'].append(int(split[2]))
        data['division'].append(int(split[3]))
        data['country'].append(split[4]) 
        data['time'].append(float(split[5]))

Text

Boston Marathon 2012

plt.hist(data['time'], 20, edgecolor='black')
plt.title('2012 Boston Marathon')
plt.xlabel('Minutes to Complete Race')
plt.ylabel('Number of Runners')
plt.show()

Text

Boston Marathon 2012

Python black box

data-fil

Python-program

Resultater

Hvordan se inn i den svarte boksen?

 

  • lag en tellevariabel for linjenummer
  • skriv ut en og en linje av det du vil se
  • splitt opp koden i flere celler

Demo i Jupyterlab

Made with Slides.com