python - 在 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]
有任何想法吗?提前致谢!
解决方案
尝试这个:
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 对时才选择它
推荐阅读
- dependency-injection - 在负载测试期间,通过构造函数类对象注入的 DI 在控制器中解析为 null
- librt - librt.so 是什么?我怎样才能直接使用它?
- python - 如何在 Python 的 ActionChains 中修复“AttributeError:'NoneType' 对象没有属性 'id”?
- matlab - 如何组合 3 个通道 L*a*b*?
- git - 从 cPanel 远程推送或克隆时权限被拒绝
- dart - 如何在 Listview.Builder 中添加一些值?
- pandas - 使用 PM/AM 将字符串更改为日期时间
- ios - UIAlertController 出现后自动关闭一小部分时间
- react-native - 尝试在反应本机应用程序上运行 jest 时测试失败。找不到“setupDevtools”错误
- android - 有什么方法可以将 FCM 消息传递的延迟控制在 1 分钟内?