【问题标题】:Filter elements of a list in Python在 Python 中过滤列表的元素
【发布时间】:2021-03-18 12:30:32
【问题描述】:

我想过滤给定列表的元素。 我有一个整数,我只想将数字保留在所有字符都小于该数字的列表中。 (现在是 5 个)。我可以为此编写更长的代码,但我想使用 filter() 编写 1 行代码。

我只做到了这一点:

def fil(l):
    return list(filter(lambda x: x<5, [int(s) for i in l for s in str(i)]))

对于l = [1,2,4,8,12],它应该回馈:

[1, 2, 4, 12]

但它会返回这个:

[1, 2, 4, 1, 2]

你能帮我解决这个问题吗?

【问题讨论】:

  • 您将其作为字符串传递。在您的列表理解中,它通过 '12' 作为 int(1) 然后 int(2)

标签: python list filter list-comprehension


【解决方案1】:

不使用filter 这可能会有所帮助:

l = [1,2,4,8,12]
results = [item for item in l if all(int(x) < 5 for x in str(item))]

如果你想一定要使用过滤器和你的函数fil,那么你有:

def fil(l):
    return list(filter(lambda item: all(int(x) < 5 for x in str(item)), l))

【讨论】:

    猜你喜欢
    • 2011-02-09
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2020-06-27
    • 1970-01-01
    相关资源
    最近更新 更多