Home > Net >  How to add specific elements from list of lists in Python
How to add specific elements from list of lists in Python

Time:11-30

Let's say I have the following list that contains other lists:

episodes = [
['1', '2', '3', '4', '5', '6', '7'], 
['1', '2', '3', '4', '5', '1', '2', '3', '4', '5', '6'], 
['1', '2', '3', '1', '2', '3', '4', '5', '6', '1', '2', '3', '4', '5', '6', '1', '2', '3', '4', '1', '2', '3']
]

Each list refer to episodes of TV-shows. For example, the first list has one season with 7 episodes, whereas the last list has five seasons with season one having 3 episodes, season 2 6 episodes and so on. I would like to save the total number of episodes for each TV-show by adding the total number of episodes for each season of the TV-show. In other words, first list is just taking the last element of that list, but the last list I have to add 3 & 6 & 6 & 4 & 3. I hope you understand what I'm trying to do. I thought about using indexing and see where the element "1" lies in each list with more than one season so I can choose the element before (number of episodes of previous season) and so one. But it gets a bit tricky doing it for all other seasons as well.

CodePudding user response:

If I understand you correctly you can just sum up the length of each list, i.e. sum(map(len, episodes))?

CodePudding user response:

if you just want the total number of episodes regardless of seasons just count the length of the each show list.

episodes = [
['1', '2', '3', '4', '5', '6', '7'], 
['1', '2', '3', '4', '5', '1', '2', '3', '4', '5', '6'], 
['1', '2', '3', '1', '2', '3', '4', '5', '6', '1', '2', '3', '4', '5', '6', '1', '2', '3', '4', '1', '2', '3']
]

print(*[len(show) for show in episodes], sep="\n")

OUTPUT

7
11
22

CodePudding user response:

I came up with something like this to check for number of episodes in each season:

episodes = [
    ['1', '2', '3', '4', '5', '6', '7', "8", "9", "10", "11"],
    ['1', '2', '3', '4', '5',
     '1', '2', '3', '4', '5', '6'],
    ['1', '2', '3',
     '1', '2', '3', '4', '5', '6',
     '1', '2', '3', '4', '5', '6',
     '1', '2', '3', '4',
     '1', '2', '3']
]


def count_episodes(list_of_episodes):
    all_episodes = [e for l in list_of_episodes for e in l]
    previous_episode = 0
    season = 1
    seasons = {}
    tmp_list = []

    for i in all_episodes:
        if previous_episode > int(i):
            seasons["season " str(season)] = tmp_list
            tmp_list = []
            season  = 1
        previous_episode = int(i)
        tmp_list.append(i)

    if len(tmp_list) > 0:
        seasons["season " str(season)] = tmp_list

    for i in seasons:
        print(i   " has {} episodes".format(len(seasons[i])))


count_episodes(episodes)

OUTPUT

season 1 has 11 episodes
season 2 has 5 episodes
season 3 has 6 episodes
season 4 has 3 episodes
season 5 has 6 episodes
season 6 has 6 episodes
season 7 has 4 episodes
season 8 has 3 episodes

CodePudding user response:

The other answers are just adding total episodes of each show. IIRC, I think you want the episode count of each season of each show:

import numpy as np
output = []
for tv_show in episodes:
    arr = np.array(tv_show)
    output.append(arr[np.where(arr=='1')[0][1:]-1].astype(int).tolist()   [int(arr[-1])])

Output:

[[7], [5, 6], [3, 6, 6, 4, 3]]

CodePudding user response:

simpler solution

At the end, it is sth as simple as:

list(map(len, episodes))
## [7, 11, 22]

If all episodes are listed always, then you can just count the total number of episodes - it will be always the same as if you determined the maximum numbers and summed them up.

slighlty more elaborate solution

from functools import reduce

def list_to_max_seasons(lst, first_element='1'):
    return reduce(lambda l, x: l   [x] if x == first_element else l[:-1]   [x], lst, [])

def sum_max_episodes(lol):
     return [(lambda l: sum([int(x) for x in l]))(list_to_max_seasons(il)) for il in lol]

Test by:

sum_max_episodes(episodes)
## [7, 11, 22]

more elaborate (recursive) solution

These solutions are not very pythonic, I admit. But they are quite universal.

def list_to_seasons(l, acc=[], by='1', tmp=[]):
    if l == []:
        return acc [tmp]
    elif l[0] == by:
        if tmp == []:
            return list_to_seasons(l[1:], acc=[], by=by, tmp=[l[0]])
        else:
            return list_to_seasons(l[1:], acc=acc [tmp], by=by, tmp=[l[0]])
    else:
        return list_to_seasons(l[1:], acc=acc, by=by, tmp=tmp [l[0]])


list_to_seasons(['1','2','3','1','2','1','2','3','1','1'])
## [['1', '2', '3'], ['1', '2'], ['1', '2', '3'], ['1'], ['1']]

Or:

def list_to_max_seasons(l, acc=[], by='1', last=None):
    if l == []:
        return acc [last]
    elif l[0] == by:
        if last is None:
            return list_to_max_seasons(l[1:], acc=[], by=by, last=l[0])
        else:
            return list_to_max_seasons(l[1:], acc=acc [last], by=by, last=l[0])
    else:
        return list_to_max_seasons(l[1:], acc=acc, by=by, last=l[0])
list_to_max_seasons(['1','2','3','1','2','1','2','3','1','1'])
## ['3', '2', '3', '1', '1']

Then:

def sum_max_episodes(lol):
     return [(lambda l: sum([int(x) for x in l]))(list_to_max_seasons(il)) for il in lol]

Test by:

sum_max_episodes(episodes)
## [7, 11, 22]
  • Related