首页 > 解决方案 > 在 Python 中使用列表理解过滤先前的索引

问题描述

我试图弄清楚如何使用列表理解在 Python 中创建一个列表,其中包含具有字符串类型并以“Test_1”、“Test_2”、“Test_3”或“Test_4”开头的项目,或者是前面的整数通过一个字符串。我还想确保所有字符串都等于“Test_1”或“Test_2”或“Test_3”或“Test_4”。

但是,我不确定如何检查该项目是否以字符串开头。

例如,我有以下列表。

['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] 

有任何想法吗?提前致谢!

标签: pythonpython-3.xlist

解决方案


尝试这个:

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))]

它需要一个 list column,然后检查前一个元素和当前元素,只有当它是 str-int 对或 int-str 对时才选择它


推荐阅读