Seite - 43 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python
Bild der Seite - 43 -
Text der Seite - 43 -
2.6 ReadingfromandWritingtoFiles 43
In some cases, it is required to run through 2 (ormore) lists at the same time.
Pythonhasahandyfunctioncalledzip for thispurpose.Anexampleofhowtouse
zip isprovided in thecodefile_handling.pybelow.
Weshouldalsobrieflymentionabout tuples,whichareverymuch like lists, the
main differencebeing that tuples cannot be changed. To a freshman, itmay seem
strange that such “constant lists” could ever bepreferable over lists. However, the
propertyofbeingconstant is agoodsafeguardagainstunintentionalchanges.Also,
it is quicker forPython tohandledata in a tuple than in a list,whichcontributes to
faster code.With thedata fromabove,wemaycreate a tuple andprint the content
bywriting
x = (’hello’, 4, 3.14, 6)
for e in x:
print ’x element: ’, e
print ’This was all the elements in the tuple x’
Tryinginsertorappend for the tuple gives an errormessage (because it cannot
bechanged), stating that the tupleobjecthasnosuchattribute.
2.6 ReadingfromandWritingtoFiles
Inputdata for aprogramoftencome fromfiles and the results of the computations
are oftenwritten to file. To illustrate basic file handling,we consider an example
wherewe readx andy coordinates fromtwocolumns in afile, applya functionf
to they coordinates, andwrite the results to a new two-columndatafile. Thefirst
lineof the inputfile is aheading thatwecan just skip:
# x and y coordinates
1.0 3.44
2.0 4.8
3.5 6.61
4.0 5.0
The relevantPython lines for reading thenumbersandwritingout a similarfileare
given in thefilefile_handling.py
filename = ’tmp.dat’
infile = open(filename, ’r’) # Open file for reading
line = infile.readline() # Read first line
# Read x and y coordinates from the file and store in lists
x = []
y = []
for line in infile:
words = line.split() # Split line into words
x.append(float(words[0]))
y.append(float(words[1]))
infile.close()
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python
- Titel
- Programming for Computations – Python
- Untertitel
- A Gentle Introduction to Numerical Simulations with Python
- Autoren
- Svein Linge
- Hans Petter Langtangen
- Verlag
- Springer Open
- Datum
- 2016
- Sprache
- englisch
- Lizenz
- CC BY-NC 4.0
- ISBN
- 978-3-319-32428-9
- Abmessungen
- 17.8 x 25.4 cm
- Seiten
- 248
- Schlagwörter
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Kategorie
- Informatik