I have created the following function:
def partidos_por_equipos(partidos, equipos):
result = []
for i in partidos:
for fecha, local, goles_local, visitante, goles_visitante in i:
if local in equipos or visitante in equipos:
result.append((fecha, local, goles_local, visitante, goles_visitante))
return result
I have had to use two loops for
because "matches" is a list that contains several sublists and these contain tuples. Ex:
partidos = [[(datetime.date(2000, 9, 9), 'FC Barcelona', 2, 'Málaga CF', 1),
(datetime.date(2000, 9, 9), 'RC Deportivo', 2, 'Athletic Club', 0)]]
The question is whether there is any function so that "matches" stays as a single list of tuples or directly accesses the tuples without having to access each sublist. And if there is no way, to know if you can save lines of code in the function that I have created. Thanks in advance.
If
partidos
it is a list with a single element (which is another list with the tuples), as is the case in your example, you just have to extract it, like this:In the more general case where you might have multiple lists inside, each containing tuples, what you want is to "flatten" the structure, ie get rid of the inner lists. You can do this like this:
and so it
aplanado
would be a list whose elements are already matches.Simplify function
Without flattening the list, the function can be reduced to one line if you make use of list comprehensions , but there are still inner loops, just inside the comprehension . So:
You can also make creative use of sets. If you make each match into a set, you can make the intersection with the team set and if that intersection is not empty, you keep the match. With this approach:
Example of operation (I consider that there is more than one list inside the main one):
If you treat it as a list, where each element is a dictionary, it becomes much clearer to read and simpler to traverse.