Python:从迭代器内的列表中删除元素?

标签 python

我正在尝试从 Python 列表中删除元素。大多数答案似乎表明使用列表迭代器是最好的,但我认为这对于我的问题来说是不可能的(或者至少是优雅的)。

我想迭代 test_data 列表并删除满足以下两个条件的任何项目:(1) 具有属性 total:sum (2) 具有属性属性 (pagePath) 以列表 mystrings 中的任何元素开头,但不等于该元素。

这是我的字符串列表和我的测试数据:

    mystrings = [u'/calculate-state-pension', u'/check-uk-visa']
    test_data = [
        {
            "pagePath": "/check-uk-visa",
            "total:sum": 2.0
        },
        {
            "pagePath": "/check-uk-visa/y",
            "total:sum": 3.0
        },
        {
            "pagePath": "/check-uk-visa/n",
            "total:sum": 4.0
        },
        {
            "pagePath": "/bank-holidays",
            "total:sum": 2.0
        },
        {
            "pagePath": "/check-uk-visa",
            "searchUniques:sum": 2.0
        }
    ]

所以我想最终得到这个列表:

    results = [
        {
            "pagePath": "/check-uk-visa",
            "total:sum": 2.0
        },
        {
            "pagePath": "/bank-holidays",
            "total:sum": 2.0
        },
        {
            "pagePath": "/check-uk-visa",
            "searchUniques:sum": 2.0
        }
    ]

这是我的代码:

    results = test_data[:]
    for r in results_copy:
        for s in mystrings:
            if 'total:sum' in r and r['pagePath'].startswith(s) \
                 and r['pagePath'] != s:
                results.remove(r)
    return results

但这似乎不起作用。它删除带有 /check-uk-visa/y 的元素,但不删除带有 /check-uk-visa/n 的元素。

我做错了什么?我认为这与删除和迭代器有关 - 看起来它正在跳过元素。

最佳答案

您需要任何组合,其中“pagePath”值以字符串列表中的字符串开头但不等于该字符串。

for dic in test_data[:]:
    s = dic.get("pagePath","")
    if "total:sum" in dic and any(s.startswith(y) and s != y  for y in mystrings):
        test_data.remove(dic)

[{'total:sum': 2.0, 'pagePath': '/check-uk-visa'}, {'total:sum': 2.0, 'pagePath': '/bank-holidays'}, {'searchUniques:sum': 2.0, 'pagePath': '/check-uk-visa'}]

需要注意的是,如果您的 mystrings 列表中有类似的字符串,其中一个字符串可能以相同的字母开头并且不相等,但可能与另一个相等,因此在这种情况下,我们可以使用一组进行 0(1) 查找并使用英寸。

mystrings = {u'/calculate-state-pension', u'/check-uk-visa'}

for dic in test_data[:]:
    s = dic.get("pagePath","")
    if "total:sum" in dic and any(s.startswith(y) for y in mystrings)and s not in mystrings:
        test_data.remove(dic)
print(test_data)

关于Python:从迭代器内的列表中删除元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28268282/

相关文章:

python - 在一条语句中将文件拆分为字典

python - scikit-learn 中的 TFIDFVectorizer 应该如何工作?

javascript - 如何将 jQuery 范围 slider 值获取到表单中以存储在 Django 的数据库中

python - Flask 多个 URL 处理程序部分处理 URL

python - image_to_string 在 Mac 中不起作用

python - 如何使用scrapy获取匹配的行号

python - 如何构造一个适合 numpy 排序的数组?

python - 使用 Freebase API 时如何从 mqlread() 获取光标?

python - 没有条件的 if 语句

python - wxPython 对话框 : "Enter" keyboard button would not "ok" the dialog