如何从嵌套列表中删除项

2024-09-29 01:33:28 发布

您现在位置:Python中文网/ 问答频道 /正文

给我一份排名投票名单和一份要淘汰的候选人名单,我需要返回一份新的排名投票名单,其中要淘汰的候选人名单中的所有候选人都已被删除

这是我到目前为止试过的代码

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

我的第一次doctest失败了,结果是:

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

Tags: innewforgreenelementitemcandidatelist
3条回答

这是必需的功能。它搜索子列表:

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))

输出:

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

使用sets变得非常简单

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']]

或:

result = [list(set(x).difference(to_eliminate)) for x in ballots]
result
[[], ['GREEN'], ['BLOC']]
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)

印刷品

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

相关问题 更多 >