python - 如何从 SQL 或 Python 中的 ```grep``` 模拟 ```WHERE``` 以迭代和更改具有某些属性的数据?
问题描述
我正在寻找一种快速简单的工具来模拟WHERE
SQL。在对象的集合(列表、集合、字典等)中(每个对象都应该是列表或类实例),我想只挑选具有某些特定属性/属性的对象并处理它们。
示例 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 为奇数的对象。
在这两个示例中,针对满足特定条件的特定属性扫描对象集合并返回要处理的那些对象。
解决方案
如果 item 是 int,你可以检查你的循环,比如
isinstance(item, int)
推荐阅读
- python - 为什么乌龟窗口不响应?
- c++ - 是否可以将 webdriver 链接到 c++ 程序作为单个可执行文件?
- python - 将 conda pip 优先于 pip
- docker - Docker 守护进程和 Docker 引擎有什么区别?
- operating-system - 如何计算硬盘一个扇区的字节数
- postgresql - PostgreSQL 使用 json 按列过滤
- linux - /dev/disk 中的不可变名称
- angular - 在Angular 7中订阅相同的服务调用而不多次调用服务
- sql - postgresql 得到最接近的timestemp结果
- r - 根据条件替换为列中的多个元素