首页 > 解决方案 > 如何从 SQL 或 Python 中的 ```grep``` 模拟 ```WHERE``` 以迭代和更改具有某些属性的数据?

问题描述

我正在寻找一种快速简单的工具来模拟WHERESQL。在对象的集合(列表、集合、字典等)中(每个对象都应该是列表或类实例),我想只挑选具有某些特定属性/属性的对象并处理它们。

示例 1:

stuff = {
    "item1":[1,2,3],
    "item2":[4,5,6,7,8,9],
    "item3":[2,4,5]
}

def myfunc(this): # this is the dict above
    result = list()
    for item in this:
        if len(item) == 3:
            result.append(item)
    return result

在示例 1 中,myfunc模拟return items in stuff WHERE len(item)==3在字典中查找并返回长度为 3 的对象stuff

示例 2:

class thing:
    def init(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

item1 = thing(1,2,3)
item2 = thing(2,3,4)
item3 = thing(3,5,7)
test_list = [item1, item2, item3]

def func(this): # this is the test_list
    result = list()
    for item in this:
        if item.a % 2:
            result.append(item)
    return result

在示例 2 中,func模拟return items in test_list WHERE (item.a % 2) == 1返回 object.a 为奇数的对象。

在这两个示例中,针对满足特定条件的特定属性扫描对象集合并返回要处理的那些对象。

标签: pythonloopsiteratoriteration

解决方案


如果 item 是 int,你可以检查你的循环,比如

isinstance(item, int)

推荐阅读