Python 如何使用列表理解比较和删除嵌套列表的第二个元素?
因此,我有一个嵌套列表,并希望根据条件匹配比较和删除嵌套列表中的列表 这是我的密码:Python 如何使用列表理解比较和删除嵌套列表的第二个元素?,python,list-comprehension,Python,List Comprehension,因此,我有一个嵌套列表,并希望根据条件匹配比较和删除嵌套列表中的列表 这是我的密码: def secondValue(val): return val[1] if __name__ == '__main__': nestedList=[] for _ in range(int(input())): name = input() score = float(input()) nestedList.append([name,
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]]
问题:
只需迭代嵌套列表的第二个子列表对于嵌套列表[1]中的x
是一个子列表,它永远不能等于x
lowerstmarks
newList = [[x, y] for x, y in nestedList if y != lowestMarks]
错误在下面的行中,现在已修复
newList=[x for x in nestedList if x[1] != lowestMarks] # PROBLEM HERE
nestedList[1]获取第二个子列表。你想反复浏览整个列表。非常感谢兄弟,这真的很有帮助。谢谢兄弟。谢谢你的帮助。我相信这将有助于其他面临这一问题的人。:)