python - 从 python 中的列表中删除所有整数

标签 python python-3.x list

如何删除列表中除最后一个整数之外的所有整数?

来自

mylist = [('a',1,'b',2,'c',3), ('d',1,'e',2),('f',1,'g',2,'h',3,'i',4)]

[('a','b','c',3), ('d','e',2),('f','g','h','i',4)]

我尝试执行以下操作,但没有任何反应。

no_integers = [x for x in mylist if not isinstance(x, int)]

最佳答案

使用 filter 进行打包的一种方法:

[(*filter(lambda x: isinstance(x, str), i), j) for *i, j in mylist]

输出:

[('a', 'b', 'c', 3), ('d', 'e', 2), ('f', 'g', 'h', 'i', 4)]

说明:

  1. for *i, j in mylist:打包 mylist 的元素(即 ('a',1,'b',2 ,'c',3), ...) 到直到最后的所有内容 (*i) 和最后 (j)。

    因此它将产生 (('a',1,'b',2,'c'), 3) 等等。

  2. filter(lambda x: isinstance(x, str), i):来自 i:('a',1,'b',2,'c' ),仅过滤掉 str 对象。

    因此 ('a',1,'b',2,'c') 变为 ('a','b','c')

  3. (*filter, j):将2的结果解包到最后一个元素为j的元组中。

    所以它变成了('a', 'b', 'c', 3)

关于python - 从 python 中的列表中删除所有整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70179736/

相关文章:

python - 使用 Pip 1.5 安装外部的、未验证的包

python - 类型错误: 'in <string>' 需要字符串作为左操作数,而不是列表(列表理解)

SwiftUI - 从列表中删除项目崩溃并出现 fatal error : Index out of range

python - 'pip==9.0.1' 分布未找到,应用程序需要

python - 制作所有可能的对称 4x4 像素图像

python - 在Python中导入颜色科学模块时出现"TypeError"

python - 如何在Django中从服务器以缩进行显示user_list?

python - 按范围排列列表

css - 带有CSS的水平列表中的乱码元素

python - 使用python和RSA算法的加密聊天应用程序