【问题标题】:How to zip items in 2 lists only when a condition is met - python如何仅在满足条件时压缩 2 个列表中的项目 - python
【发布时间】:2019-07-30 09:43:42
【问题描述】:

当我有两个列表时:

list1 = ['course1', 'course2', 'course3', 'course4', 'course5']
list2 = [12, 3, 3, 4, 5]

我只想在满足条件时将索引列表项压缩在一起。否则对于列表索引项:0。

【问题讨论】:

  • 全部压缩,然后过滤。
  • 您的预期结果是什么?
  • 您将它们压缩到什么数据结构中?我建议将它们全部压缩,然后删除任何不满足条件的(键,值)对。
  • “我只想在 number >= 5.5 时将索引项压缩在一起” 什么是索引项?

标签: python arrays list zip


【解决方案1】:

使用map()进行压缩:

list1 = ['course1', 'course2', 'course3', 'course4', 'course5']
list2 = [12, 3, 3, 4, 5]

m = map(lambda x, y: (x, y) if y > 5.5 else None, list1, list2)
list(filter(None.__ne__, m))
# [('course1', 12)]

【讨论】:

    【解决方案2】:

    忘记 zip 并创建自己的解决方案:

    list1 = ['course1', 'course2', 'course3', 'course4', 'course5']
    list2 = [12, 3, 3, 4, 5]
    
    
    def zip_condition(list_a, list_b, func):
        iter_a = iter(list_a)
        iter_b = iter(list_b)
        while 1:
            try:
                a, b = next(iter_a), next(iter_b)
            except StopIteration:
                return
            if func((a, b)):
                yield (a, b)
    
    
    result = list(zip_condition(list1, list2, lambda x: x[1] >= 5.5))
    print(result)
    

    【讨论】:

      【解决方案3】:

      我建议使用列表理解的较短版本:

      [x for x in zip(list1, list2) if x[1] >= 5.5]

      【讨论】:

        【解决方案4】:

        如果您想从list1 和list2 中获取列表的压缩列表,条件是list2 的项目应该是>=5.5,然后试试这个:

        list3 = [[i,j] for i,j in zip(list1, list2) if j>=5.5]
        

        输出:

        [['course1', 12]]
        

        【讨论】:

          猜你喜欢
          • 2013-06-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-24
          • 2017-11-02
          相关资源
          最近更新 更多