purplerain
purplerain

Reputation: 13

How do you eliminate items from nested lists

Given a list of ranked ballots and a list of candidates to eliminate, I need to return a new list of ranked ballots where all the candidates in the list of candidates to eliminate have been removed.

This is the code I've tried so far

import doctest 

def eliminate_candidate(ballots, to_eliminate):
    '''
    (list, list) -> list

    >>> eliminate_candidate([['NDP', 'LIBERAL'], ['GREEN', 'NDP'], \
    ['NDP', 'BLOC']], ['NDP', 'LIBERAL'])
    [[], ['GREEN'], ['BLOC']]
    >>> eliminate_candidate([], [])
    []
    >>> eliminate_candidate([[]], [])
    [[]]
    '''
    new_list = []

    # Copy ballots onto new list
    for item in ballots:
        new_list.append(item)

    for item in new_list:
        for element in item:
            if element in to_eliminate:
                item.remove(element)

    return new_list

My first doctest is failing, giving me this output instead:

[['LIBERAL'], ['GREEN'], ['BLOC']]

Upvotes: 1

Views: 47

Answers (3)

igorkf
igorkf

Reputation: 3565

Using sets becomes pretty easy!

ballots = [['NDP', 'LIBERAL'], ['GREEN', 'NDP'], ['NDP', 'BLOC']]
to_eliminate = ['NDP', 'LIBERAL']

result = [list(set(x) - set(to_eliminate)) for x in ballots]
result
[[], ['GREEN'], ['BLOC']]

Or:

result = [list(set(x).difference(to_eliminate)) for x in ballots]
result
[[], ['GREEN'], ['BLOC']]

Upvotes: 2

User
User

Reputation: 826

ballots = [['NDP', 'LIBERAL'], ['GREEN', 'NDP'], ['NDP', 'BLOC']]
to_eliminate = ['NDP', 'LIBERAL']

res = [[element for element in b if element not in to_eliminate] for b in ballots]
print(res)

prints

[[], ['GREEN'], ['BLOC']]

Upvotes: 1

quamrana
quamrana

Reputation: 39374

This is the function required. It searches through the sublists:

def eliminate_candidate(ballots, to_eliminate):
    return [[party for party in ballot if party not in to_eliminate] for ballot in ballots]

ballots = [['NDP', 'LIBERAL'], ['GREEN', 'NDP'], ['NDP', 'BLOC']]
to_eliminate = ['NDP', 'LIBERAL']

print(eliminate_candidate(ballots, to_eliminate))

Output:

[[], ['GREEN'], ['BLOC']]

Upvotes: 1

Related Questions