列出对休息的理解 [英] list comprehensions with break

查看:77
本文介绍了列出对休息的理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在清单理解的一行中编写以下代码.

I have the following code that I would like to write in one line with a list comprehension.

list1 = [4, 5, 6, 9, 10, 16, 21, 23, 25, 27]
list2 = [1, 3, 5, 7, 8, 11, 12, 13, 14, 15, 17, 20, 24, 26, 56]

list3 = []
for i in list1:
    for j in list2:
        if j>i:
            # print(i,j)
            list3.append(j)
            break
print(list1)
print(list3)

输出为:

[4, 5, 6, 9, 10, 16, 21, 23, 25, 27]
[5, 7, 7, 11, 11, 17, 24, 24, 26, 56]

是让我失望的break语句,我不知道该放在哪里.

It's the break statement that throws me off, I don't know where to put it.

谢谢

推荐答案

您不能真正破坏列表理解的内部for循环,您可以做的是避免使用下一个函数来找到它完全破坏它首次出现匹配值:

You can't really break a list comprehension's internal for loop, what you can do is avoid having to break it at all by using the next function to find the first occurrence of a matching value:

list1 = [4, 5, 6, 9, 10, 16, 21, 23, 25, 27]
list2 = [1, 3, 5, 7, 8, 11, 12, 13, 14, 15, 17, 20, 24, 26, 56]
list3 = [ next(j for j in list2 if j>i) for i in list1 ]

输出:

print(list1)
print(list3)
[4, 5, 6, 9, 10, 16, 21, 23, 25, 27]
[5, 7, 7, 11, 11, 17, 24, 24, 26, 56]

如果您担心性能(因为列表理解将比循环慢),则可以在列表2中使用二等分搜索来找到下一个更高的值:

If you are concerned about performance (since the list comprehension will be slower than the loops), you could use a bisecting search in list 2 to find the next higher value:

from bisect import bisect_left
list3 = [ list2[bisect_left(list2,i+1)] for i in list1 ]

这假定list2以升序排序,并且max(list2)> max(list1)

这篇关于列出对休息的理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆