使用两个列表列出理解

时间:2014-12-09 18:06:37

标签: python list list-comprehension

如果我有这样的列表(请注意,它会在5121926之后跳过一个...等等6132027都缺失了):

lst1 = [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 49, 50, 51, 52, 53, 54, 56, 57, 58, 59, 60, 61]

我有一个这样的列表(这代表哪个跳过)

lst2 = [0,2] # this means the 0'st skip and 2nd skip which is 13)

并合并lst1lst2

我想制作一个lst3

的新[0, 1, 2, 3, 4, 5, 14, 15, 16, 17, 18, 19]

我不知道我的解释是否有意义,但我基本上想要使用两个列表中的值并创建一个新列表。这就是我尝试过的:

lst1 = [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 49, 50, 51, 52, 53, 54, 56, 57, 58, 59, 60, 61]

def colorChecker(color):
    for c in color: 
    return 6 + 7 * color

lst3 = [ p for p in lst1 if p < colorChecker([0,2])] 

这似乎仅适用于colorChecker[0],而不适用于colorChecker[1]

2 个答案:

答案 0 :(得分:1)

如果您已经知道缺失元素的位置,则lst1 。您的代码变得如此简单:

>>> lst2 = [0, 2]
>>> lst3 = []
>>> for i in lst2:
        lst3.extend(range(7*i, 7*i+6))


>>> lst3
[0, 1, 2, 3, 4, 5, 14, 15, 16, 17, 18, 19]

答案 1 :(得分:0)

由于lst2中的每个元素似乎都引用了来自lst1的6个元素的组,我首先会创建一个像

这样的块的列表
[lst1[i*6:(i+1)*6] for i in lst2]

...评估为

== [lst1[0*6:(0+1)*6], lst1[2*6:(2+1)*6]]
== [lst1[0:6], lst1[12:18]]
== [[0, 1, 2, 3, 4, 5], [14, 15, 16, 17, 18, 19]]

最后,您只需flatten该列表即可获得结果。