Learning Python data structures. this document is generated by code itself I hope you enjoy it.
A string is a sequence of characters.
oneString = "hello" #>>> hello
anotherString = "world!" #>>> world!The contatenate operator it the + symbol.
gretting = oneString + " " + anotherString #>>> hello world!The len function take a string argument and returns interger representing the length of a string.
len(gretting) #>>> 12Looping through strings
index = 0
while index < len(greetting):
letter = fruit[index]
index = index + 1
print(letter)
for letter in greetting:
print(letter)
#both loops will print:
#>> h
#>> e
#>> l
#>> l
#>> o
#>>
#>> w
#>> o
#>> r
#>> l
#>> d
#>> !The split method divide the string by the white spaces, returning a list with the resulting strings.
It takes an optional string argument in order to change the delimiter.
sentence = "With three words."
words = sentence.split() # returns ["With", "three", "words."]In Python you can obtain the instance of a file by using the open built-in function.
File is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed unless closefd is set to False.).
Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.
Open Syntax
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode.
| Char | Meaning |
|---|---|
| 'r' | open for reading (default) |
| 'w' | open for writing, truncating the file first |
| 'x' | open for exclusive creation, failing if the file already exists |
| 'a' | open for writing, appending to the end of file if it exists |
| 'b' | binary mode |
| 't' | text mode (default) |
| '+' | open for updating (reading and writing) |
Example of the code that writes this document:
try:
file = open("README.md", "w")
file.write(content)
print("File writed.")
except:
print("Error: can't read or write file.")File.read() Reads a whole file returning a string.
File.readlines() Reads the file returning an array of a string per line.
fHanddler = open(fileName, "r")
lines = fHanddler.readlines()
for line in lines:
print(line)Here's the output of a function that reads the first 10 lines of this very file:
# Python Data Structures
Learning Python data structures. this document is generated by code itself I hope you enjoy it.
## String
A string is a sequence of characters.
```python
oneString = "hello" #>>> hello
List are collection of data.
leonidas = ["This", "is", "Sparta!"]
len(stringList) # returns 3The range function an integer representing a size
and returns a list ordered numbers starting from 0.
for i in range(len(stringList)):
print(i, stringList[i])The contateantion operator + concatenates lists returning a new list.
result = ""
messenger = ["\nMessenger:", "This", "is", "madness..."]
leonidas = ["\nLeonidas:", "Madness?", "This", "is", "Sparta!"]
dialog = messenger + leonidas
for word in dialog:
result += word + " "
print(result)
'''
Messenger: This is madness...
Leonidas: Madness? This is Sparta!
'''The in operator returns a boolean if a value belongs to a list.
leonidas = ["This", "is", "Sparta!"]
if("Sparta!" in leonidas):
return TrueAdds an element to de end of the list.
ages = [18, 22, 30, 25]
ages.append(27) # now: [18, 22, 30, 25, 27]Extend the list by appending all the items from the iterable.
ages = [18, 22, 30, 25]
ages.extend([27, 19, 37]) # now: [18, 22, 30, 25, 27, 19, 37]Insert an item at a given position. The first argument is the index of the element before which to insert.
ages = [18, 22, 30, 25]
ages.insert(0, 27) # now: [27, 18, 22, 30, 25]Removes the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.
ages = [18, 22, 30, 25]
ages.remove(25) # now: [18, 22, 30]Removes the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list.
ages = [18, 22, 30, 25]
ages.pop() # now: [18, 22, 30]
ages.pop(0) # now: [22, 30]Remove all items from the list.
ages = [18, 22, 30, 25]
ages.clear() # now: []Return zero-based index in the list of the first item whose is equal to the argument passed in the first position. Can take 2 optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument. Raises a ValueError if there is no such item.
ages = [18, 22, 30, 25]
ages.index(30) # returns: 2Return the number of times given value appears in the list.
ages = [18, 22, 30, 25]
ages.count(18) # returns: 1Sort the items of the list in place.
ages = [18, 22, 30, 25]
ages.sort() # now: [18, 22, 25, 30]Reverse the elements of the list in place.
ages = [18, 22, 30, 25]
ages.reverse() # now: [25, 30, 22, 18]Return a shallow copy of the list.
ages = [18, 22, 30, 25]
ages.copy() # returns: [18, 22, 30, 25]Dictonaries are colection of data strored in key-value paris.
The in operator:
count = dict()
names = ["Ismael", "Ruben", "Sohany", "Sohany", "Ismael", "Ismael"]
for name in names:
if name not in count:
conunt[name] = 1
else:
count[name] += 1
for key, value in count: # supports 2 iteration variables.
print(key, value)
# Prints the following:
# Ismael 3
# Ruben 1
# Sohany 2The list function takes a dictionary instance and returns a list of it.
keyArray = list(count.keys()) # ["Ismael", "Ruben", "Sohany"]
valueArray = list(count.values()) # [3, 1, 2]
itemArray = list(count.items()) # [("Ismael", 3), ("Ruben", 1), ("Sohany", 2)]cesarCount = count.get("Cesar", 0) # There no key Cesar in count so cesarCount = 0
ismaelCount = count.get("Ismael", 0) # ismaelCount = 3Tuples are immutable sequences, typically used to store collections of heterogeneous data (such as the 2-tuples produced by the enumerate() built-in).
Tuples are also used for cases where an immutable sequence of homogeneous data is needed (such as allowing storage in a set or dict instance).
tuple('abc') # returns ('a', 'b', 'c')
tuple( [1, 2, 3] ) # returns (1, 2, 3)Tuples assignment:
person = ("fred", 21)
name, age = person
print(name) # prints: fred
print(age) # prints: 21The > & < operators
(0, 23) > (-1, 24) # returns True
(0, 23) < (0, 24) # returns True
("Zod", "apple") > ("angel", "Ponking") # returns false
("Bob", "joe") < ("Bob", "tim") # returns falseimport files
def wordCount(lineList: List[str])-> dict:
result = dict()
for line in lineList:
for word in line.split():
result[word] = result.get(word, 0) + 1
return result
def sortDictByValue(dictionary: dict[str, int])-> List[tuple[int, str]]:
result: List[tuple[int, str]] = []
for word, count in dictionary:
result.append(tuple(count, word))
return sorted(result, reverse=True)
sortedList = tuples.sortDictByValue(tuples.wordCount(files.readFile(fileName)))Here the result:
| Word | Times |
|---|---|
| the | 59 |
| = | 45 |
| # | 34 |
| ``` | 32 |
| ```python | 30 |
| a | 28 |
| of | 26 |
| in | 26 |
| is | 22 |
| ### | 22 |
Ismael Varela, Fulstack Developer