Docsity

Schemi Comput: Python Lists e Dictionaries - Prof. Silvello, Appunti di Programmazione e Tecnologie Web

Toggle sidebar
bg1
SCHEMI COMPUT
December 20, 2020
1 Phyton Lists
[13]: #indexes goes from 0 to n-1
#access elements in a list
L=[5,2,4,6,3,1]
#access elements by index
print(L[3])
#return the last element of the list
print(L[-1])
print(L[len(L)-1])
#the result of len is obtained by counting all the elements in a list
print(len(L))
6
1
1
6
[9]: #nested lists
L1 =[10, [1,2], [3,4,6]]
#access the first nested list
print(L[1])
#access the first element of the first nested list
print(L[1][0])
print(len(L1))
print(len(L1[2]))
[1, 2]
1
3
1
pf3
pf4
pf5
pf8
pf9
pfa

Anteprima parziale del testo

Scarica Schemi Comput: Python Lists e Dictionaries - Prof. Silvello e più Appunti in PDF di Programmazione e Tecnologie Web solo su Docsity!

SCHEMI COMPUT

December 20, 2020

1 Phyton Lists

[13]: #indexes goes from 0 to n- #access elements in a list

L = [5, 2, 4, 6, 3, 1]

#access elements by index print(L[3])

#return the last element of the list print(L[-1]) print(L[len(L)-1])

#the result of len is obtained by counting all the elements in a list print(len(L))

[9]: #nested lists

L1 = [10, [1,2], [3, 4, 6]]

#access the first nested list print(L[1])

#access the first element of the first nested list print(L[1][0])

print(len(L1)) print(len(L1[2]))

[1, 2] 1 3

[15]: L2 = ['cc', 'dd', ['eee', 'fff']]

#use ranges to subset a list L2[0:2]

[15]: ['cc', 'dd']

[16]: #open range till the end L2[0:]

[16]: ['cc', 'dd', ['eee', 'fff']]

18: ['cc', 'dd']

[19]: #print only the nested list L2[2][0:2]

[19]: ['eee', 'fff']

2 Maniputaliting lists

[26]: #1°: updating an element in a list

list1 = [23, 34, 56, 22]

#change 34 into 74 list1[1] = 45 print(list1)

#update multiple elements list1[1:3] = [50, 60]

list

[23, 45, 56, 22]

[26]: [23, 50, 60, 22]

[28]: #2°: add an element in a list

list1 = [23, 34, 56, 22]

#add an element at the end of the list

L1.index(34)

[46]: #search an item in a list print(60 in L1) print(23 in L1)

False True

3 Phyton Dictionaries

47: dic = {'a': 1, 'b': 2, 'c': [3,4]}

#access an element in a dic: access elements by key dic['a']

[48]: #add elements in a dic dic['z'] = "pippo" dic

[48]: {'a': 1, 'b': 2, 'c': [3, 4], 'z': 'pippo'}

[49]: #update elements in a list dic['a'] = [5, 20] dic

[49]: {'a': [5, 20], 'b': 2, 'c': [3, 4], 'z': 'pippo'}

[50]: #delete elements from a dic del (dic['b']) dic

[50]: {'a': [5, 20], 'c': [3, 4], 'z': 'pippo'}

#iterate over keys print(dic.keys())

#iterate over values print(dic.values())

#iterate over items print(dic.items())

dict_keys(['a', 'c', 'z']) dict_values([[5, 20], [3, 4], 'pippo']) dict_items([('a', [5, 20]), ('c', [3, 4]), ('z', 'pippo')])

4 Merging dictionaries

[52]: d1 = {'a': 1, 'b': 3} d2 = {'c': 7, 'd': 9}

d1.update(d2) print(d1)

{'a': 1, 'b': 3, 'c': 7, 'd': 9}

[53]: #unpack operator ** d3 = {**d1, **d2} print(d3)

{'a': 1, 'b': 3, 'c': 7, 'd': 9}

5 Input/output

File = contiguos set of bytes used to store data 3 main parts: 1. Header = metadata about the contents of the file 2. Data = contents as written by the creator/editor 3. End of file = special character that indicates the end of the file File path = string that represents the location of the file It is required to access a file 3 parts: 1. Folder path = file folder location 2. File name = actual name of the file 3. Extension = end of the file path pre-pended with a “.” (file type)

[57]: #open() built-in function

open('hello.txt')

[57]: <_io.TextIOWrapper name='hello.txt' mode='r' encoding='UTF-8'>

#strip() = removes extra space and extra content (removes EOL characters) lines = [] for line in open('hello.txt'): lines.append(line.strip()) print(lines)

7 Writing to files

There are 2 methods to write into a file: write( ) or writelines( ) methods These methods create a file if it’s not present in the folder you’re working with, otherwise they overwrite the file with the new content

[81]: outfile = open('hello.txt', 'w')

#you have to use \n if you want to write into a new line outfile.write("this is the line of the new file \n ") outfile.writelines("this is another line of the new file") outfile.close()

with open('hello.txt') as infile: print(infile.readlines())

['this is the line of the new file\n', 'this is another line of the new file']

[82]: with open('hello.txt') as infile: for line in infile: print(line.strip())

this is the line of the new file this is another line of the new file

[90]: #create a file without empty lines

#create a new empty text file newfile = open("halloween.txt", 'w')

with open("halloween.txt", 'r') as oldfile: for line in oldfile: #isspace() method: returns true if the line is empty if not (line.isspace()): newfile.write(line)

newfile.close()

8 Appending to a file

append( ): starts writing at the end of the file

[94]: with open('hello.txt', 'a') as sampletext: sampletext.write(' \n new line of new file \n ')

[92]: with open('hello.txt') as sampletext: print(sampletext.readlines())

['this is the line of the new file\n', 'this is another line of the new file\n', ' new line of new file \n']

9 OS Module

OS module in Phtyon: provides functions for interacting with the operating system [95]: #import statement import os

[96]: #method: os.name print(os.name)

posix

[98]: #getcwd() function: returns the current working dir = tells you where you are print(os.getcwd())

/Users/matildecoppoli/Desktop/UNIPD/I SEMESTRE/COMPUT THINKING/PHYTON

[99]: #mkdir() function: create a new directory in the current path os.mkdir("tmp_folder")

[100]: #listdir() function: returns the list of all files and directories in the ␣ ↪→ current path print(os.listdir())

['tmp_folder', 'SCHEMI COMPUT.ipynb', 'exercises.ipynb', '01_Python_Basics_CT2020.pdf', '09-2020-CT-Sorting.pdf', '.DS_Store', 'halloween.txt', '09_Python_exercises-Solutions.ipynb', '02_Python_Basics-2.pdf', 'computational dicembre.pages', '05_Python_Dictionaries.pdf', '09.02_CT2020_Silvello_sorting.pdf', '10-2020-CT- FileSystem.pdf', '03_Python_Conditionals.pdf', 'computational dicembre.pdf', '09_Python_exercises-Copy1.ipynb', '[NO ES] 10_Python_DataAnalysis.ipynb', '04_Python_Loops.pdf', '.ipynb_checkpoints', '07_Python_IO.pdf', '08_Python_OS.pdf', 'hello.txt', '06_Python_Functions.pdf']

[101]: #rmdir() function: removes the specified directory only if it's empty #we can not remove the cwd os.rmdir("tmp_folder") print(os.listdir())

['SCHEMI COMPUT.ipynb', 'exercises.ipynb', '01_Python_Basics_CT2020.pdf', '09-2020-CT-Sorting.pdf', '.DS_Store', 'halloween.txt', '09_Python_exercises- Solutions.ipynb', '02_Python_Basics-2.pdf', 'computational dicembre.pages',

('09.02_CT2020_Silvello_sorting', '.pdf') filename: 10-2020-CT-FileSystem.pdf ('10-2020-CT-FileSystem', '.pdf') filename: 03_Python_Conditionals.pdf ('03_Python_Conditionals', '.pdf') filename: computational dicembre.pdf ('computational dicembre', '.pdf') filename: 09_Python_exercises-Copy1.ipynb ('09_Python_exercises-Copy1', '.ipynb') filename: [NO ES] 10_Python_DataAnalysis.ipynb ('[NO ES] 10_Python_DataAnalysis', '.ipynb') filename: 04_Python_Loops.pdf ('04_Python_Loops', '.pdf') filename: 07_Python_IO.pdf ('07_Python_IO', '.pdf') filename: 08_Python_OS.pdf ('08_Python_OS', '.pdf') filename: hello.txt ('hello', '.txt') filename: 06_Python_Functions.pdf ('06_Python_Functions', '.pdf') filename: exercises-checkpoint.ipynb ('exercises-checkpoint', '.ipynb') filename: 08_Python_OS-checkpoint.ipynb ('08_Python_OS-checkpoint', '.ipynb') filename: SCHEMI COMPUT-checkpoint.ipynb ('SCHEMI COMPUT-checkpoint', '.ipynb') filename: eliminare-checkpoint.ipynb ('eliminare-checkpoint', '.ipynb') filename: 09_Python_exercises-Copy1-checkpoint.ipynb ('09_Python_exercises-Copy1-checkpoint', '.ipynb')

[107]: #print all the pdfs in the cwd for (dirpath, dirnames, filenames) in os.walk(os.getcwd()): for filename in filenames: ext = os.path.splitext(filename)[1] if (ext == ".pdf"): print(filename)

01_Python_Basics_CT2020.pdf 09-2020-CT-Sorting.pdf 02_Python_Basics-2.pdf 05_Python_Dictionaries.pdf 09.02_CT2020_Silvello_sorting.pdf 10-2020-CT-FileSystem.pdf 03_Python_Conditionals.pdf computational dicembre.pdf 04_Python_Loops.pdf

07_Python_IO.pdf 08_Python_OS.pdf 06_Python_Functions.pdf

[108]: #print how many pdfs in each folder of the cwd for (dirpath, dirnames, filenames) in os.walk(os.getcwd()): i = 0 for filename in filenames: ext = os.path.splitext(filename)[1] if (ext == ".pdf"): i+= print(i)

[109]: #print how many pdfs in total i = 0 for (dirpath, dirnames, filenames) in os.walk(os.getcwd()): for filename in filenames: ext = os.path.splitext(filename)[1] if (ext == ".pdf"): i+= print(i)

12

[110]: #print the files contained in the cwd only if they are pdf (without extension) fileList = os.listdir() for file in fileList: if (os.path.splitext(file)[1] == ".pdf"): print(os.path.splitext(file)[0])

01_Python_Basics_CT 09-2020-CT-Sorting 02_Python_Basics- 05_Python_Dictionaries 09.02_CT2020_Silvello_sorting 10-2020-CT-FileSystem 03_Python_Conditionals computational dicembre 04_Python_Loops 07_Python_IO 08_Python_OS 06_Python_Functions