Python中带有条件的对象的过滤列表



我有一个这样的列表结构:

listpost =
[
{
"post_id":"01",
"text":"abc",
"time": datetime.datetime(2021, 8, 5, 15, 53, 19),
"type":"normal",
},
{
"post_id":"02",
"text":"nothing",
"time":datetime.datetime(2021, 8, 5, 15, 53, 19),
"type":"normal",
}
]

如果只有[text]有"abc">

我想通过[text]键中的文本过滤列表所以这个例子看起来像这样

listpost =
[
{
"post_id":"01",
"text":"abc",
"time": datetime.datetime(2021, 8, 5, 15, 53, 19),
"type":"normal",
}
]

我代码:

from facebook_scraper import get_posts
listposts = []
for post in get_posts("myhealthkkm", pages=1):
listposts.append(post)
print(listposts)

既然您特别询问了关于过滤列表的问题,那么您可以使用lambda内置的filter来过滤列表中的元素。

>>> list(filter(lambda x: x.get('text', '')=='abc', listpost))
[{'post_id': '01', 'text': 'abc', 'time': datetime.datetime(2021, 8, 5, 15, 53, 19), 'type': 'normal'}]

但我建议在实际将其附加到列表之前将其过滤掉,以避免由于需要重复项而进行不必要的计算,即只附加符合条件的项。

像这样:

for post in get_posts("myhealthkkm", pages=1):
if <post match the condition>:
listposts.append(post)  # append the post

这样简单:

filtered_list = [e for e in listpost if e['text'] == 'abc']

如果您想要过滤恰好是"abc">

new_list = [el for el in listpost if el["text"]=="abc"]

如果你想保留以"abc"开头的元素

new_list = [el for el in listpost if el["text"].startswith("abc")]

如果你想保留包含"abc"子字符串

new_list = [el for el in listpost if "abc" in el["text"]]
list(filter(lambda x: x['text']=='abc', listpost))

希望这行得通

已经给出了一个很好的python解决方案,但这里有另一个更接近您所尝试的解决方案:

from facebook_scraper import get_posts
listposts = []
wanted = "abc"  # wanted post
for post in get_posts("myhealthkkm", pages=1):
if t:=post.get("text", "") == wanted:
# print("Found", t)
listposts.append(post) 
else:
pass
# print("Not found")
print(listposts)

最新更新