【问题标题】:How to compare and remove second element of a nested list using List comprehensions?如何使用列表推导比较和删除嵌套列表的第二个元素?
【发布时间】:2019-07-07 06:10:10
【问题描述】:

所以我有一个嵌套列表,想根据条件匹配比较和删除嵌套列表中的列表。

这是我的代码:

def secondValue(val):
    return val[1]


if __name__ == '__main__':
    nestedList=[]
    for _ in range(int(input())):
        name = input()
        score = float(input())
        nestedList.append([name,score]) # Made a nested list from the input 
    lowestMarks=min(nestedList,key=secondValue) [1]  #Extracting the minimum score 
    newList=[x for x in nestedList[1] if x!=lowestMarks] # PROBLEM HERE

我的代码的最后一行是我想根据条件匹配删除嵌套列表中的列表。当然,我可以使用嵌套的 for 循环来做到这一点,但如果有办法使用列表理解来做到这一点,我会考虑这种方法。

基本上,我很欣赏一个告诉如何根据条件从嵌套列表中删除列表的答案。就我而言,列表如下所示:

[[test,23],[test2,44],......,[testn,23]] 

【问题讨论】:

    标签: python list-comprehension


    【解决方案1】:

    问题:

    • for x in nestedList[1] 只是迭代嵌套列表的第二个子列表。

    • x 是一个子列表,它永远不能等于lowestMarks。

    使用列表理解为:

    newList = [[x, y] for x, y in nestedList if y != lowestMarks]
    

    【讨论】:

    • 非常感谢兄弟,真的很有帮助。
    【解决方案2】:

    错误出现在下面一行,现在已修复。

    newList=[x for x in nestedList if x[1] != lowestMarks] # PROBLEM HERE
    

    nestedList[1] 获取第二个子列表。您想遍历整个列表。

    【讨论】:

    • 谢谢兄弟。感谢您的帮助。我很肯定它会帮助其他面临这个问题的人。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 2020-02-28
    • 2019-07-13
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多