【问题标题】:In Python, how can I remove certain data from list to create a new one?在 Python 中,如何从列表中删除某些数据以创建新数据?
【发布时间】:2018-06-19 18:58:30
【问题描述】:

我正在从一个 json 端点提取数据,该端点返回一个列表。

这个列表中的一些元素,我想扔掉。我只对某些元素感兴趣。

我是这样提取数据的:

# Pull the data
url = "https://my-endpoint.com"
user = 'user1'
pwd = 'password1'
response = requests.get(url, auth=(user, pwd))
data = json.loads(response.text)

有效载荷类似于:

[{
        "apples": {
            "value": 0.0
        },
        "oranges": {
            "value": 0.0
        },
        "name": "testing123"
    },
    {
        "apples": {
            "value": 0.0
        },
        "oranges": {
            "value": 0.0
        },
        "name": "foobar"
    },
    {
        "apples": {
            "value": 0.0
        },
        "oranges": {
            "value": 0.0
        },
        "name": "testing456"
    }]

假设上面继续使用许多其他元素,但名称不同。如何提取所有数据,但排除我想要的?

从上面的示例中,我想提取名称“testing123”和“testing456”的所有数据,但排除“foobar”中的数据。

我将迭代新列表以提取我需要的数据。

【问题讨论】:

  • 有效负载已损坏,请发布一个有效的。
  • 构建一个只包含您想要的项目的列表理解:[item for item in data if item['name'] in ('testing123', 'testing456')]
  • 抱歉,我已经更新了 json 有效负载。

标签: python json loops python-requests


【解决方案1】:

您的问题中有很多不匹配的大括号,但我想我已经弄清楚了。您在一个列表中有 3 个(+ 更多)字典,每个字典都有自己的 apples、oranges(或其他)键,然后是 name 键。您需要一个与此结构相同的字典列表,只需要name in set_of_preapproved_names 所在的字典。为简洁起见,我假设您有一个名为 OK_NAMES 的名称列表:

new_data = [Dict for Dict in data if Dict ["name"] in OK_NAMES]

你去!

如果您想消除所有具有特定模式的名称:

new_data = [Dict for Dict in data if not Dict ["name"].startswith ("foobar")]

应该可以的


顺便说一句,我知道在类型之后命名变量几乎从来都不是一个好主意,我只是为了清楚起见。

【讨论】:

  • 在这种情况下,假设还有一堆名为“foobar123”和“foobar456”的元素。如何消除以 foobar 开头的项目?
  • 哦,所以您不想要特定名称,您只想排除特定名称(或命名模式)?
  • @hippe21 我为你编辑了我的答案,相同的逻辑只是不同的条件
  • 是的,我的错没有说得更清楚。仍然是堆栈上的菜鸟! :)
  • 李维谢谢你!还有@John Gordon,也谢谢你。这正是我所追求的。非常简单!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多