繁体   English   中英

如何从嵌套列表中消除项目

[英]How do you eliminate items from nested lists

给定一个排名选票列表和一个要消除的候选人列表,我需要返回一个新的排名选票列表,其中要消除的候选人列表中的所有候选人都已被删除。

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

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 失败了,而是给了我这个 output:

[['LIBERAL'], ['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']]

这是所需的 function。 它搜索子列表:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM