【问题标题】:How to filter array with particular ID in Python?如何在 Python 中过滤具有特定 ID 的数组?
【发布时间】:2021-10-09 09:42:03
【问题描述】:

我有一个从我的网络抓取中附加的输出列表。

for post in get_posts("test", pages=50):
    print(post)
    listposts.append(post)

实际输出:

{'post_id': '1', 'text': 'abc'}
{'post_id': '2', 'text': 'haha'}
{'post_id': '3', 'text': 'abc'}
{'post_id': '4', 'text': 'haha'}


如何让它只显示 text with abc ? :

预期输出:

{'post_id': '1', 'text': 'abc'}
{'post_id': '3', 'text': 'abc'}

【问题讨论】:

标签: python arrays json


【解决方案1】:

在您的循环中添加一个if 条件以有条件地附加到您的listposts 列表中

for post in get_posts("test", pages=50):
    print(post)
    if "abc" in post["text"]: 
        listposts.append(post)

使用if post["text"] == "abc": 进行精确匹配

【讨论】:

  • 感谢您的回复,但当我打印出来时,它会在列表帖子中不断返回相同的值Image
  • @johnny2000 对你告诉我的内容无能为力
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-23
  • 2019-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多