python将美丽的套装输出转换为设置?
在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个问题:
如何将
visibil_texts
转换为 in line中的集合?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:
How to convert
visible_texts
into set in one line?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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
dict
保存插入顺序。dict
s包含键值对。在这种情况下,您不在乎该值,因此始终设置为true
。我不太确定您要使用
filter
与始终返回true
的函数来实现什么。请澄清。您可以使用设置理解
注意,注意,注意,注意, 注意,注意,请注意但是,插入顺序不一定保留。
dict
s preserve insertion order.dict
s contain key-value pairs. In this case, you don't care about the value, so it's always set toTrue
.I'm not too sure what you are trying to achieve by using
filter
with a function that always returnsTrue
. Please clarify.You can apply the strip function by using a set comprehension:
Note, however, that the insertion order is not necessarily preserved.