python - 从具有特定键值的字典列表中删除元素
问题描述
我有一堆地理位置保存为字典列表。其中一个关键是国家 ID,我想删除所有国家 ID 不是 112 的位置。我写了这段代码。由于某种原因,它删除了大多数非 112 条目,但并未删除所有条目。这是我为此过滤编写的循环:
counter = 0
i=0
while counter < len(CS_list):
country = CS_list[i]["AddressInfo"].get("CountryID")
if country != 112:
CS_list.pop(i)
else:
i += 1
counter += 1
这是运行此循环后的列表。正如你所看到的,仍然有一些非 112,尽管很多这样的条目已被删除。这真的让我很困惑。知道为什么会这样吗?
编辑: 这是输入列表元素的示例。运行循环后,我希望拥有相同的列表,但没有国家 ID 不同于 112 的所有元素。
解决方案
通常,您只需构建一个仅包含您想要的元素的新列表。
countries = [
{'AddressInfo': {'CountryID': 112}},
{'AddressInfo': {'CountryID': 8}},
{'AddressInfo': {'CountryID': 2}},
{'AddressInfo': {'CountryID': 4}},
{'AddressInfo': {'CountryID': 112}},
]
countries = [
country for country in countries
if country.get('AddressInfo', {}).get('CountryID') == 112
]
print(countries)
如果您明确想要从现有列表中删除这些条目,您可以将列表推导的结果作为切片分配给原始列表:
countries[:] = [
country for country in countries
if country.get('AddressInfo', {}).get('CountryID') == 112
]
推荐阅读
- javascript - 如何将来自 javascript 的信息存储到 Django 模型中?
- php - 如何从客户端而不是从服务器或我的 Web 应用程序获取数据?
- javascript - 如何获取数字数组并返回数字加倍的数组?
- python - Python 包执行逻辑回归,连续目标在 0 和 1 之间?
- reactjs - 如何链接 mongo 数据库中的两个项目?
- html - 全屏和地理位置按钮在我的网络地图中不起作用
- ios - 上下文闭包类型 '(Data?, URLResponse?, Error?) -> Void' 需要 3 个参数,但 1 在闭包主体中使用
- android-fragments - 将 Xamarin.Forms 片段嵌入导致“孩子已经有父母”崩溃的片段中
- javascript - javascript on form 选项传递两个值,一个用于隐藏/可见功能,第二个用于数据值
- r - 代码不再适用于在 R 中的 vegan 中更改 metaMDS 中点的形状/颜色