【问题标题】:Comparing each element of a list to their corresponding index in another将列表的每个元素与另一个列表中的相应索引进行比较
【发布时间】:2018-08-09 11:34:08
【问题描述】:

我有一个清单:

list1=[1,2,3,4,5,6]

我需要将此与一系列其他列表进行比较:

list2=[[0,0,0,0,0,0],[0,1,2,3,4,5],[2,2,2,2,2,2],[5,4,3,2,1,0]]

并标记其中任何一个,其中 list1 中的每个值都大于其在 list2[n] 中相应索引的值,即:

list1[0]>list2[n][0], list1[1]>list2[n][1], list1[2]>list2[n][2], list1[3]>list2[n][3], list1[4]>list2[n][4], list1[5]>list2[n][5]

这里应该返回TRUE, TRUE, FALSE, FALSE

list1 和 list2[n] 的长度始终相同,但这个长度可以不同。

【问题讨论】:

    标签: python comparison list-comprehension


    【解决方案1】:

    使用zip 和列表推导从list1 和list2[n] 中获取一对元素,然后使用all 检查是否所有对 (x,y), x>y

    >>> list1=[1,2,3,4,5,6]
    >>> list2=[[0,0,0,0,0,0],[0,1,2,3,4,5],[2,2,2,2,2,2],[5,4,3,2,1,0]]
    >>> [all(x>y for x,y in zip(list1,lst)) for lst in list2]
    [True, True, False, False]
    

    如果list1 和list2[n] 的大小不相等,请将zip 替换为itertools.zip_longest

    >>> from itertools import zip_longest
    >>> [all(x>y for x,y in zip_longest(list1,lst, fillvalue=0)) for lst in list2]
    [True, True, False, False]
    

    【讨论】:

      猜你喜欢
      • 2019-01-19
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 2015-04-02
      • 1970-01-01
      • 2013-06-06
      • 1970-01-01
      • 2021-02-18
      相关资源
      最近更新 更多