python - 删除带有外国字母号码的列表

标签 python list

我正在学习使用列表,并且我想到了如何删除包含任何外国数字或字母的列表?

假设我有一个列表:[['c', 'b', 'a', 'd', 'a'], ['c', 'd', 'a', ' a', 'b'], ['d', 'a', 'a', 'c', 'b'], ['d', 'a', 'c', 'a', 'b' ], ['a', 'c', 'a', 'b', 'd'], ['d', 'c', 'b', 'a', 'a'], ['d' , 'c', 'b', 'a', 'a'], ['a', 'a', 't', 'j', 'a']]

我想删除带有“t”和“j”的列表(最后一个列表)。我想说“如果存在“0”、“1”、“2”或“3”以外的值,则删除该列表”但我不知道该怎么做。我知道有“any”和“all”等运算符,但是是否有相当于“other”的运算符?

到目前为止我已经尝试过

 for item in listt:
     if any(('a','b','c','d')) not in item:
        data.remove(item)

但这会删除仅包含外来项目的列表 我需要它来删除除 a b c 和 d 之外的所有外来字符(128 个 ascii 字符或更多)

最佳答案

"if there are values other than "0", "1", "2" or "3", then delete the list"

您可以使用set.difference()查看是否还有其他值 [0, 1, 2, 3]。

您可以使用list comprehension迭代所有列表:

foo = [['c', 'b', 'a', 'd', 'a'], ... , ['a', 'a', 't', 'j', 'a']]
reference_list = set('abcd')

[l for l in foo if not (set(l) - reference_list)]

结果:

[['c', 'b', 'a', 'd', 'a'],
 ['c', 'd', 'a', 'a', 'b'],
 ['d', 'a', 'a', 'c', 'b'],
 ['d', 'a', 'c', 'a', 'b'],
 ['a', 'c', 'a', 'b', 'd'],
 ['d', 'c', 'b', 'a', 'a'],
 ['d', 'c', 'b', 'a', 'a']]

set.difference() 将为您提供两个唯一集合之间的不同值,可用于查看您的案例中是否有任何其他值。

列表推导式优于 for 循环,但它们本质上做同样的事情,如果 for 循环更容易理解,您可以将上面的表达式分解为 for 循环,它看起来像这样:

new_foo = []
for l in foo:
    if not (set(l) - reference_list):
        new_foo.append(l)

编辑:

编辑后查看您的:如果有(('a','b','c','d'))不在项目中。我假设您正在尝试删除所有不包含 all [a, b, c, d] 的列表。

您可以通过更改 set.difference 的优先级来简单地做到这一点:

(reference_list - set(l))

虽然这不会接受 ['a', 'a', 'b', 'b'] 作为有效列表,但另一个会接受。


预定义要比较的引用列表。感谢@Eric Duminil 的评论。

关于python - 删除带有外国字母号码的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47218675/

相关文章:

c# - 从 PropertyInfo 创建通用列表 <Type>

list - F# - 创建带有条件元素的列表

java - 如何在 Java 中的每第 n 个项目之后将项目添加到列表中

python - python中的内部类评估顺序

python - 将三列之间的数学运算结果附加到下一行

python - 扩展 django 管理模板

python - 根据输入对大列表进行切片

python - 相对日志模块中创建

python - 从 0-d numpy 数组中恢复字典

python - Pandas - 数据框名称列表?