Introdução a Python¶

Aula 3¶

Sumário¶

  • Coleções de dados
  • Exercícios

Coleções de dados¶

List¶

[]: Utilizam-se para representar uma lista

In [1]:
my_list = [1, 2, 3]

type(my_list)
Out[1]:
list

list(): Construtor utilizado para criar uma lista

In [2]:
this_list = list("volvo")

type(this_list)
Out[2]:
list

Propriedades de uma lista:

  • Permite duplicados
In [3]:
duplicates_list = [2, 2]

duplicates_list
Out[3]:
[2, 2]
  • Permite vários tipos diferentes
In [4]:
diff_types_list = [1, "sand", 1.75, True]

diff_types_list
Out[4]:
[1, 'sand', 1.75, True]
  • Ordenada

Os seus elementos têm uma ordem definida e essa ordem não se irá alterar. Consequentemente, podem ser acedidos através de um índice.

  • Mutável

É possível alterar, adicionar e remover itens numa lista, após esta ter sido criada.

Aceder a elementos¶

In [5]:
colors = ["blue", "red", "yellow"] #índices começam em 0

colors[2]
Out[5]:
'yellow'
In [6]:
transports = ["car", "plane", "bike"] #neste caso, o índice -1 refere-se ao último elemento

transports[-2]
Out[6]:
'plane'
In [7]:
vegetables = ["carrot", "brocolli", "mushroom", "spinach"]

vegetables[1:]
Out[7]:
['brocolli', 'mushroom', 'spinach']
In [8]:
animals = ["cat", "dog", "bird", "elephant", "zebra"]

animals[:2]
Out[8]:
['cat', 'dog']
In [9]:
food = ["spaghetti", "burguer", "pizza"]

food[1:2]
Out[9]:
['burguer']
In [10]:
prog_languages = ["C", "C#", "C++", "Java", "R"]

prog_languages[-4:-1]
Out[10]:
['C#', 'C++', 'Java']

Alterar elementos¶

In [11]:
vowels = ["a", "e", "i", "o", "u"]

vowels[2] = "I"

vowels
Out[11]:
['a', 'e', 'I', 'o', 'u']
In [12]:
subjects = ["maths", "physics", "geometry", "chemistry"]

subjects[1:3] = ["english", "german"]

subjects
Out[12]:
['maths', 'english', 'german', 'chemistry']
In [13]:
countries = ["portugal", "denmark", "mozambique", "brazil"]

countries[1:2] = ["belgium", "switzerland"]

countries
Out[13]:
['portugal', 'belgium', 'switzerland', 'mozambique', 'brazil']
In [14]:
cities = ["viseu", "coimbra", "aveiro"]

cities[1:3] = ["braga"]

cities
Out[14]:
['viseu', 'braga']

Adicionar elementos¶

In [15]:
numbers = ["one", "two", "three"]

numbers.append("four")

numbers
Out[15]:
['one', 'two', 'three', 'four']
In [16]:
sports = ["football", "tennis"]

sports.insert(1, "rugby")

sports
Out[16]:
['football', 'rugby', 'tennis']
In [17]:
apparel = ["trousers", "skirts"]
shoes = ["boots", "slippers"] #também poderia ser um tuplo, por exemplo

apparel.extend(shoes)

apparel
Out[17]:
['trousers', 'skirts', 'boots', 'slippers']

Remover elementos¶

In [18]:
planets = ["mercury", "venus", "earth", "pluto"]

planets.remove("pluto")

planets
Out[18]:
['mercury', 'venus', 'earth']
In [19]:
summer = ["sun", "beach"]

summer.clear()

summer
Out[19]:
[]
In [20]:
body_parts = ["arms", "legs", "head"]

body_parts.pop(1) #se o índice não for especificado, remove o último elemento

body_parts
Out[20]:
['arms', 'head']
In [21]:
body_parts = ["arms", "legs", "head"]

del body_parts[1]

body_parts
Out[21]:
['arms', 'head']

Listas em compreensão¶

newlist = [expression for item in iterable if condition == True]: Sintaxe de uma lista em compreensão (a condição é opcional)

In [22]:
plants = ["rose", "cactus", "bamboo", "daisy"]

plants_with_s = []

for plant in plants:
    if "s" in plant:
        plants_with_s.append(plant)
        
plants_with_s
Out[22]:
['rose', 'cactus', 'daisy']
In [23]:
plants = ["rose", "cactus", "bamboo", "daisy"]

plants_with_s = [plant for plant in plants if "s" in plant]

plants_with_s 
Out[23]:
['rose', 'cactus', 'daisy']
In [24]:
birds = ["chicken", "blackbird", "flamingo"]

birds_fixed = [bird if bird!="blackbird" else "common blackbird" for bird in birds] 

birds_fixed
Out[24]:
['chicken', 'common blackbird', 'flamingo']

Ordenar listas¶

In [25]:
weekdays = ["monday", "Tuesday", "wednesday", "thursday", "friday"]

weekdays.sort() #também funciona para números

weekdays
Out[25]:
['Tuesday', 'friday', 'monday', 'thursday', 'wednesday']
In [26]:
makeup = ["blush", "eyeshadow", "lipgloss"]

makeup.sort(reverse=True)

makeup
Out[26]:
['lipgloss', 'eyeshadow', 'blush']
In [27]:
def my_sort_function(x):
    return abs(x)

x = [-17, -1, 3, -2, 4]

x.sort(key=my_sort_function)

x
Out[27]:
[-1, -2, 3, 4, -17]
In [28]:
weekend = ["saturday", "sunday"]

weekend.reverse()

weekend
Out[28]:
['sunday', 'saturday']

Copiar listas¶

In [29]:
months = ["january", "february", "march"]

new_list = months.copy()

new_list
Out[29]:
['january', 'february', 'march']
In [30]:
months = ["january", "february", "march"]

my_new_list = list(months)

my_new_list
Out[30]:
['january', 'february', 'march']

Outros métodos relevantes¶

  • count()
In [31]:
money = ["euro", "pound", "dollar", "euro"]

money.count("euro")
Out[31]:
2
  • index()
In [32]:
teams = ["slbenfica", "fcporto", "scbraga"]

teams.index("fcporto")
Out[32]:
1

Tuple¶

(): Utilizam-se para representar um tuplo

In [33]:
my_tuple = (1,2,3) #para criar um tuplo com um único elemento, é necessário colocar uma vírgula no fim

type(my_tuple)
Out[33]:
tuple

tuple() - Construtor utilizado para criar um tuplo

In [34]:
this_tuple = tuple((4,8))

type(this_tuple)
Out[34]:
tuple

Propriedades de um tuplo:

  • Permite duplicados
In [35]:
duplicates_tuple = (2,2)

duplicates_tuple
Out[35]:
(2, 2)
  • Permite vários tipos diferentes
In [36]:
diff_types_tuple = (2, "ana", 3.45, False)

diff_types_tuple
Out[36]:
(2, 'ana', 3.45, False)
  • Ordenado

Os seus elementos têm uma ordem definida e essa ordem não se irá alterar. Consequentemente, podem ser acedidos através de um índice.

  • Imutável

Não é possível alterar, adicionar e remover itens num tuplo, após este ter sido criado.

Aceder a elementos¶

Análogo à lista

Desconstruir tuplos¶

In [37]:
specialty = ("cardiology", "dermatology", "neurology")

(heart, skin, brain) = specialty

print(heart)
print(skin)
print(brain)
cardiology
dermatology
neurology
In [38]:
books = ("The Great Gatsby", "Don Quixote", "War and Peace", "Anna Karenina")

(fitzgerald, cervantes, *tolstoi) = books

print(fitzgerald)
print(cervantes)
print(tolstoi)
The Great Gatsby
Don Quixote
['War and Peace', 'Anna Karenina']

Métodos¶

Análogos aos que foram mencionados na última secção relativa à lista

Set¶

{}: Utilizam-se para representar um conjunto

In [39]:
my_set = {1,2,3} #caso não tenha elementos já não se trata de um conjunto, mas sim de um dicionário

type(my_set)
Out[39]:
set

set() - Construtor utilizado para criar um conjunto

In [40]:
this_set = set(("banana", "apple", "orange"))

type(this_set)
Out[40]:
set

Propriedades de um conjunto:

  • Não permite duplicados
In [41]:
no_duplicates_set = {"tree", "tree"}

no_duplicates_set
Out[41]:
{'tree'}
  • Permite vários tipos diferentes
In [42]:
diff_types_set = {2, "cinema", 5.67, False}

diff_types_set
Out[42]:
{2, 5.67, False, 'cinema'}
  • Não ordenado

Os seus elementos não têm uma ordem definida e essa ordem pode alterar-se. Consequentemente, não podem ser acedidos através de um índice ou de uma chave.

  • Mutável

É possível adicionar e remover itens num conjunto, após este ter sido criado.

Adicionar elementos¶

In [43]:
singers = {"Lady Gaga", "Shakira"}

singers.add("Beyoncé")

singers
Out[43]:
{'Beyoncé', 'Lady Gaga', 'Shakira'}
In [44]:
bands = {"Maroon 5", "The Script"}
dead_bands = {"Nirvana", "Queen"} #também poderia ser uma lista, por exemplo

bands.update(dead_bands)

bands
Out[44]:
{'Maroon 5', 'Nirvana', 'Queen', 'The Script'}

Remover elementos¶

In [45]:
jewelry = {"ring", "earring", "bracelet"}

jewelry.remove("ring")

jewelry
Out[45]:
{'bracelet', 'earring'}
In [46]:
jewelry = {"ring", "earring", "bracelet"}

jewelry.discard("ring")

jewelry
Out[46]:
{'bracelet', 'earring'}
In [47]:
weather = {"sunny", "rainy", "foggy"}

weather.pop()

weather
Out[47]:
{'rainy', 'sunny'}
In [48]:
periodic_table = {"mg", "na", "li"}

periodic_table.clear()

periodic_table
Out[48]:
set()

Juntar sets¶

In [49]:
living_painters = {"Cindy Sherman", "Liu Xiaodong"}
dead_painters = {"Vincent van Gogh", "Pablo Picasso"}

painters = living_painters.union(dead_painters)

painters
Out[49]:
{'Cindy Sherman', 'Liu Xiaodong', 'Pablo Picasso', 'Vincent van Gogh'}
In [50]:
it_brands = {"microsoft", "apple", "google"}
fruits = {"apple", "cherry", "strawberry"}

it_brands.intersection_update(fruits)

it_brands
Out[50]:
{'apple'}
In [51]:
x = {1,2,3}
y = {3,4,5}

z = x.intersection(y)

z
Out[51]:
{3}
In [52]:
motorcycle_brands = {"ducati", "yamaha"}
piano_brands = {"yamaha"}

motorcycle_brands.symmetric_difference_update(piano_brands)

motorcycle_brands
Out[52]:
{'ducati'}
In [53]:
chocolate_cake_ingredients = {"eggs", "sugar", "flour", "chocolate"}
strawberry_cake_ingredients = {"eggs", "sugar", "flour", "strawberry"}

flavours = chocolate_cake_ingredients.symmetric_difference(strawberry_cake_ingredients)

flavours
Out[53]:
{'chocolate', 'strawberry'}

Outros métodos relevantes¶

  • issuperset()
In [54]:
s1 = {"a", "b", "c", "d", "e"}
s2 = {"a", "b"}

s1.issuperset(s2)
Out[54]:
True
  • issubset()
In [55]:
set1 = {1,2}
set2 = {1,2,3,4}

set1.issubset(set2)
Out[55]:
True
  • isdisjoint()
In [56]:
first_set = {True, False}
second_set = {False}

first_set.isdisjoint(second_set)
Out[56]:
False
  • copy()
In [57]:
original_set = {"ball"}
copied_set = original_set.copy()

copied_set
Out[57]:
{'ball'}
  • difference()
In [58]:
a = {1.5, 3.45}
b = {4.75, 1.5}

c = a.difference(b)

c
Out[58]:
{3.45}
  • difference_update()
In [59]:
d = {True, 3}
e = {3, 4}

d.difference_update(e)

d
Out[59]:
{True}

Dictionary¶

{}: Utilizam-se para representar um dicionário

In [60]:
my_dict = {
    "name": "John",
    "surname": "Doe",
    "job": "lawyer"
}

type(my_dict)
Out[60]:
dict

dict() - Construtor utilizado para criar um dicionário

In [61]:
this_dict = dict({"ground": "bus", "air": "airplane", "water": "boat"})

type(this_dict)
Out[61]:
dict

Propriedades de um dicionário:

  • Não permite chaves duplicadas
In [62]:
no_duplicates_dict = {
    "university": "Minho",
    "location": "Braga",
    "campus": "Azurém",
    "campus": "Gualtar"
}

no_duplicates_dict #o valor duplicado irá sobrescrever o valor existente
Out[62]:
{'university': 'Minho', 'location': 'Braga', 'campus': 'Gualtar'}
  • Permite vários tipos diferentes
In [63]:
computer = {
    "brand": "Toshiba",
    "touch": True,
    "colors": ["grey", "black", "white"]
}

computer
Out[63]:
{'brand': 'Toshiba', 'touch': True, 'colors': ['grey', 'black', 'white']}
  • Ordenado (a partir da versão 3.7)

Os seus elementos têm uma ordem definida e essa ordem não se irá alterar. Consequentemente, podem ser acedidos através de uma chave.

  • Mutável

É possível alterar, adicionar e remover itens num dicionário, após este ter sido criado.

Aceder a elementos¶

In [64]:
song = {
    "name": "Grenade",
    "artist": "Bruno Mars",
    "year": 2010
}

song["year"]
Out[64]:
2010
In [65]:
song = {
    "name": "Grenade",
    "artist": "Bruno Mars",
    "year": 2010
}

song.get("year")
Out[65]:
2010
In [66]:
show = {
    "name": "The Ellen DeGeneres Show",
    "TV host": "Ellen DeGeneres",
    "country of origin": "USA" 
}

show.keys()
Out[66]:
dict_keys(['name', 'TV host', 'country of origin'])
In [67]:
cr7 = {
    "team": "Manchester United",
    "children": 4,
    "nationality": "Portuguese"
}

cr7.values()
Out[67]:
dict_values(['Manchester United', 4, 'Portuguese'])
In [68]:
car = {
    "brand": "Volkswagen",
    "color": "grey",
    "year": 2016
}

car.items()
Out[68]:
dict_items([('brand', 'Volkswagen'), ('color', 'grey'), ('year', 2016)])

Alterar elementos¶

In [69]:
sports_club = {
    "name": "FC Barcelona",
    "stadium": "Camp Nou",
    "coach": "Pep Guardiola"
}

sports_club["coach"] = "Ronald Koeman"

sports_club
Out[69]:
{'name': 'FC Barcelona', 'stadium': 'Camp Nou', 'coach': 'Ronald Koeman'}
In [70]:
sports_club = {
    "name": "FC Barcelona",
    "stadium": "Camp Nou",
    "coach": "Pep Guardiola"
}

sports_club.update({"coach": "Ronald Koeman"})

sports_club
Out[70]:
{'name': 'FC Barcelona', 'stadium': 'Camp Nou', 'coach': 'Ronald Koeman'}

Adicionar elementos¶

Análogo à secção anterior

Remover elementos¶

In [71]:
singer = {
    "name": "Amy Winehouse",
    "sex": "female",
    "age": 27,
    2008: ["Album of the Year", "Record of the Year"]
}

singer.pop("age")

singer
Out[71]:
{'name': 'Amy Winehouse',
 'sex': 'female',
 2008: ['Album of the Year', 'Record of the Year']}
In [72]:
singer = {
    "name": "Amy Winehouse",
    "sex": "female",
    "age": 27,
    2008: ["Album of the Year", "Record of the Year"]
}

del singer["age"]

singer
Out[72]:
{'name': 'Amy Winehouse',
 'sex': 'female',
 2008: ['Album of the Year', 'Record of the Year']}
In [73]:
country = {
    "name": "Portugal",
    "money": "euro",
    "language": "portuguese"
}

country.popitem()

country
Out[73]:
{'name': 'Portugal', 'money': 'euro'}
In [74]:
cat = {
    "date of birth": "30th of september of 2020",
    "colors": ["white", "black", "yellow"]
}

cat.clear()

cat
Out[74]:
{}

Copiar dicionários¶

Análogo à lista

Outros métodos relevantes¶

  • fromkeys()
In [75]:
keys = ("monday", "tuesday", "wednesday")
values = "weekday"

new_dict = dict.fromkeys(keys, values)

new_dict
Out[75]:
{'monday': 'weekday', 'tuesday': 'weekday', 'wednesday': 'weekday'}
  • setdefault()
In [76]:
game = {
    "name": "LoL",
    "mode": "multiplayer",
    "year": 2009
}

game.setdefault("developer", "Riot Games")

game
Out[76]:
{'name': 'LoL', 'mode': 'multiplayer', 'year': 2009, 'developer': 'Riot Games'}

Exercícios¶

1) Escreva uma função que recebe uma lista e retorna um par com o primeiro e o último elemento dessa lista.

2) Escreva uma função que retorna um conjunto com os elementos que existem apenas no primeiro conjunto e não no segundo conjunto.

3) Escreva uma função que retorna o maior elemento de uma lista.

4) Escreva uma função que retorna a distância euclidiana entre dois pontos.

5) Escreva uma função que retorna a soma dos números que são múltiplos de 3 ou 5 entre 1 e um limite, sendo que esse limite é um parâmetro.

6) Escreva uma função que filtra a altura e o peso de estudantes, características estas que, por sua vez, estão armazenadas num dicionário.

7) Escreva uma função que retorna todas as combinações de pares de 0 até um limite, com recurso a uma lista em compreensão.

8) Escreva uma função que retorna o resultado de somar os elementos de cada tuplo presente numa lista de tuplos.

9) Escreva uma função que retorna os $n$ menores números de uma lista de números.

10) Escreva uma função que recebe uma lista de listas de números e retorna a sublista que resulta na maior soma.