python将美丽的套装输出转换为设置?

发布于 2025-02-07 07:40:06 字数 612 浏览 2 评论 0原文

在python中,我有:

def tag_visible(element):
    return True


def get_visible_text(soup):
    text_tags = soup.find_all(text=True)
    visible_texts = filter(tag_visible, text_tags)
    stripped = set()
    for text in visible_texts:
        stripped.add(text.strip())
    return stripped

我有2个问题:

  1. 如何将visibil_texts转换为 in line中的集合?

  2. python中是否有数据结构,例如集合(无重复)并保留元素的顺序?


更新:

我可以做:

return set(visible_texts)

但是如何应用strip 函数

In python I have:

def tag_visible(element):
    return True


def get_visible_text(soup):
    text_tags = soup.find_all(text=True)
    visible_texts = filter(tag_visible, text_tags)
    stripped = set()
    for text in visible_texts:
        stripped.add(text.strip())
    return stripped

I have 2 questions:

  1. How to convert visible_texts into set in one line?

  2. Is there a data structure in python like set (no duplicates) and preserves order of elements?


UPDATE:

I can do:

return set(visible_texts)

But how to apply strip function?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雪化雨蝶 2025-02-14 07:40:06

dict保存插入顺序。 dict s包含键值对。在这种情况下,您不在乎该值,因此始终设置为true

我不太确定您要使用filter与始终返回true的函数来实现什么。请澄清。

def get_visible_text(soup):
    text_tags = soup.find_all(text=True)
    return dict((text.strip(), True) for text in text_tags)

您可以使用设置理解

return set(text.strip() for text in visible_texts)

注意,注意,注意,注意, 注意,注意,请注意但是,插入顺序不一定保留。

dicts preserve insertion order. dicts contain key-value pairs. In this case, you don't care about the value, so it's always set to True.

I'm not too sure what you are trying to achieve by using filter with a function that always returns True. Please clarify.

def get_visible_text(soup):
    text_tags = soup.find_all(text=True)
    return dict((text.strip(), True) for text in text_tags)

You can apply the strip function by using a set comprehension:

return set(text.strip() for text in visible_texts)

Note, however, that the insertion order is not necessarily preserved.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文