代码之家  ›  专栏  ›  技术社区  ›  Jordan Williams

在Python中使用列表理解来过滤上一个索引

  •  0
  • Jordan Williams  · 技术社区  · 5 年前

    但是,我不知道如何检查项目前面是否有字符串。

    例如,我有以下列表。

    ['Test_3', 80, 'Test_4', 80, 90, 'Test_1', 0, 'Test_2', 0]
    

    ['Test_3', 80, 'Test_4', 80, 'Test_1', 0, 'Test_2', 0]
    

    以下是我目前所掌握的情况。

    column = [x for x in column if type(x) is str and x == "Test_1" or x == "Test_2" or x == "Test_3" or x == "Test_4" or type(x) is int] 
    

    2 回复  |  直到 5 年前
        1
  •  1
  •   adrtam    5 年前

    试试这个:

    columns = [x for i, x in enumerate(column) if (i==0 and isinstance(x,(int,str))) or (isinstance(x,str) and isinstance(column[i-1], int)) or (isinstance(x,int) and isinstance(column[i-1],str))]
    

    这需要一张单子 column ,然后检查前一个元素和当前元素,仅当它是str int pair或int str pair时才选择它

        2
  •  0
  •   Transhuman    5 年前

    itertools.groupby

    from itertools import groupby
    
    column = ['Test_3', 80, 'Test_4', 80, 90, 'Test_1', 0, 'Test_2', 0]
    [list(g)[0] for _, g in groupby(column,lambda x:isinstance(x,int))]
    #['Test_3', 80, 'Test_4', 80, 'Test_1', 0, 'Test_2', 0]
    
        3
  •  0
  •   Igor Rivin    5 年前

    这里有一个简单的解决方案:

    import itertools
    pairlist = [[column[i], column[i+1]] for i in range(len(column)-1)]
    goodpairlist = [i for i in pairlist if isinstance(i[0], str)]
    list(itertools.chain(*goodpairlist)
    
    推荐文章