集合

未匹配的标注
本文档最新版为 4.0,旧版本可能放弃维护,推荐阅读最新版!

简介

Collection类提供了一个流畅,方便的包装器来处理数据列表。

它位于返回多个结果的每个 ORM 和查询构建器查询的后面。例如,检查以下代码:

users = User.all()
names = users.map(lambda user: user.name.lower())
names = names.reject(lambda name: len(name) == 0)

这将返回非空的所有用户名。

可用方法

在本文档的其余部分中,我们将讨论Collection类上可用的每种方法。请记住,所有这些方法都可以链接在一起,以流畅地操作基础列表或字典。此外,几乎每种方法都会返回一个新的Collection实例,使您可以在必要时保留该集合的原始副本。

方法清单

all()

all方法仅返回集合表示的基础列表或字典:

Collection([1, 2, 3]).all()

# [1, 2, 3]

avg()

avg方法返回集合中所有项的平均值:

Collection([1, 2, 3, 4, 5]).avg()

# 3

如果集合包含嵌套对象或字典,则必须传递用于确定要计算平均值的键:

collection = Collection([
    {'name': 'JavaScript: The Good Parts', 'pages': 176},
    {'name': 'JavaScript: The Defnitive Guide', 'pages': 1096}
])

collection.avg('pages')

# 636

chunk()

chunk方法将集合分为给定大小的多个较小的集合:

collection = Collection([1, 2, 3, 4, 5, 6, 7])

chunks = collection.chunk(4)

chunks.serialize()

# [[1, 2, 3, 4], [5, 6, 7]]

collapse()

collapse方法将列表集合折叠为一个平面集合:

collection = Collection([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

collapsed = collection.collapse()

collapsed.all()

# [1, 2, 3, 4, 5, 6, 7, 8, 9]

contains()

contains方法确定集合是否包含给定的项目:

collection = Collection(['foo', 'bar'])

collection.contains('foo')

# True

您也可以使用in关键字

'foo' in collection

# True

您还可以将键/值对传递给contains,该方法将确定给定对是否存在于集合中:

collection = Collection([
    {'name': 'John', 'id': 1},
    {'name': 'Jane', 'id': 2}
])

collection.contains('name', 'Simon')

# False

最后,您还可以将回调传递给contains方法以执行自己的真实性测试:

collection = Collection([1, 2, 3, 4, 5])

collection.contains(lambda item: item > 5)

# False

count()

count方法返回集合中的项目总数:

collection = Collection([1, 2, 3, 4])

collection.count()

# 4

还可以使用len函数:

len(collection)

# 4

diff()

diff方法将集合与另一个集合,列表dict进行比较:

collection = Collection([1, 2, 3, 4, 5])

diff = collection.diff([2, 4, 6, 8])

diff.all()

# [1, 3, 5]

each()

each方法迭代集合中的项目并将每个项目传递给给定的回调:

posts.each(lambda post: post.author().save(author))

从回调中返回False以打破循环:

posts.each(lambda post: post.author().save(author) if author.name == 'John' else False)

every()

every方法都会创建一个由第 n 个元素组成的新集合:

collection = Collection(['a', 'b', 'c', 'd', 'e', 'f'])

collection.every(4).all()

# ['a', 'e']

您可以选择将偏移量作为第二个参数传递:

collection.every(4, 1).all()

# ['b', 'f']

filter()

filter方法通过给定的回调过滤集合,仅保留那些通过给定的真相测试的项目:

collection = Collection([1, 2, 3, 4])

filtered = collection.filter(lambda item: item > 2)

filtered.all()

# [3, 4]

first()

first方法返回通过给定的真实性测试的集合中的第一个元素:

collection = Collection([1, 2, 3, 4])

collection.first(lambda item: item > 2)

# 3

您也可以不带任何参数调用first方法来获取集合中的第一个元素。如果集合为空,则返回None

collection.first()

# 1

flatten()

flatten方法将多位集合转换为单维集合:

collection = Collection([1, 2, [3, 4, 5, {'foo': 'bar'}]])

flattened = collection.flatten()

flattened.all()

# [1, 2, 3, 4, 5, 'bar']

forget()

forget方法从集合中下标位置移除元素:

collection = Collection([1, 2, 3, 4, 5])

collection.forget(1)

collection.all()

# [1, 3, 4, 5]

和其他集合方法不相同的是,forget并不返回修改后的集合,它直接对传入的集合进行修改。

for_page()

for_page方法根据提供的页码返回指定页集合:

collection = Collection([1, 2, 3, 4, 5, 6, 7, 8, 9])

chunk = collection.for_page(2, 3)

chunk.all()

# 4, 5, 6

该方法需要传递一个页码和每页显示的条数。

get()

get方法根据传入的key来返回元素。如果key不存在返回None

collection = Collection([1, 2, 3])

collection.get(3)

# None

你还可以传递一个可选参数来作为默认返回值:

collection = Collection([1, 2, 3])

collection.get(3, 'default-value')

# default-value

implode()

implode方法用来拼接集合。该参数取决于集合元素的类型。

如果集合包含的是字典或者对象,你必须传递要拼接的属性,还需传递连接的拼接符:

collection = Collection([
    {'account_id': 1, 'product': 'Desk'},
    {'account_id': 2, 'product': 'Chair'}
])

collection.implode('product', ', ')

# Desk, Chair

如果集合包含仅字符串元素,那么仅传递连接拼接符即可:

collection = Collection(['foo', 'bar', 'baz'])

collection.implode('-')

# foo-bar-baz

is_empty()

is_empty方法在集合为空时返回True,否则返回为False

Collection([]).is_empty()

# True

last()

last方法返回集合条件匹配最后一个元素:

collection = Collection([1, 2, 3, 4])

last = collection.last(lambda item: item < 3)

# 2

你可以还使用无惨的last方法,它仅返回集合最后一个元素,如果集合为空的话返回None

collection.last()

# 4

map()

map方法遍历集合所有元素,并且调用回调方法,该回调方法可以修改元素.

collection = Collection([1, 2, 3, 4])

multiplied = collection.map(lambda item: item * 2)

multiplied.all()

# [2, 4, 6, 8]

和其他集合方法一样,map不会修改原本集合,而是返回一个全新集合。如果你想操作原集合,使用transform方法。

merge()

merge方法将给定列表合并到集合中:

collection = Collection(['Desk', 'Chair'])

collection.merge(['Bookcase', 'Door'])

collection.all()

# ['Desk', 'Chair', 'Bookcase', 'Door']

不像其他集合方法,merge并不返回一个新集合对象,它直接操作传递结合。

pluck()

pluck方法返回集合所有给定键的值:

collection = Collection([
    {'product_id': 1, 'product': 'Desk'},
    {'product_id': 2, 'product': 'Chair'}
])

plucked = collection.pluck('product')

plucked.all()

# ['Desk', 'Chair']

你还可以为返回的结果设置指定的键:

plucked = collection.pluck('name', 'product_id')

plucked

# {1: 'Desk', 2: 'Chair'}

pop()

pop 方法返回集合最后一个元素:

collection = Collection([1, 2, 3, 4, 5])

collection.pop()

# 5

collection.all()

# [1, 2, 3, 4]

prepend()

prepend方法增加元素到集合的起始位置:

collection = Collection([1, 2, 3, 4])

collection.prepend(0)

collection.all()

# [0, 1, 2, 3, 4]

pull()

pull方法根据键移除并返回集合元素:

collection = Collection([1, 2, 3, 4])

collection.pull(1)

collection.all()

# [1, 3, 4]

push()/append()

push(或者append)方法追加元素到集合末尾:

collection = Collection([1, 2, 3, 4])

collection.push(5)

collection.all()

# [1, 2, 3, 4, 5]

put()

put方法设置集合给定键对应的值:

collection = Collection([1, 2, 3, 4])

collection.put(1, 5)

collection.all()

# [1, 5, 3, 4]

等效于:

collection[1] = 5

reduce()

reduce方法将集合元素合成单个值,回调传入操作结果和本次迭代元素:

collection = Collection([1, 2, 3])

collection.reduce(lambda result, item: (result or 0) + item)

# 6

result首次迭代为None,你可以为reduce方法传递第二个可选参数作为迭代的初始值:

collection.reduce(lambda result, item: result + item, 4)

# 10

reject()

reject方法通过给定的回调过滤集合元素。该回调返回True时即会从集合中移除:

collection = Collection([1, 2, 3, 4])

filtered = collection.reject(lambda item: item > 2)

filtered.all()

# [1, 2]

相对的方法为reject,参考filter 方法。

reverse()

reverse方法反转集合元素排序:

collection = Collection([1, 2, 3, 4, 5])

reverse = collection.reverse()

reverse.all()

# [5, 4, 3, 2, 1]

serialize()

serialize方法将集合转换为list。如果集合值为ORM模型对象,该模型对象将转换为字典:

collection = Collection([User.find(1)])

collection.serialize()

# [{'id': 1, 'name': 'John'}]

serialize也会转换嵌套的对象,如果你想返回下级对象,请使用all方法。

shift()

shift方法从集合中删除并返回第一项:

collection = Collection([1, 2, 3, 4, 5])

collection.shift()

# 1

collection.all()

# [2, 3, 4, 5]

sort()

sort方法对集合进行排序:

collection = Collection([5, 3, 1, 2, 4])

sorted = collection.sort()

sorted.all()

# [1, 2, 3, 4, 5]

sum()

sum方法对集合所有元素总和:

Collection([1, 2, 3, 4, 5]).sum()

# 15

如果集合包含是字典或者对象,你必须传递需要汇总的键:

collection = Collection([
    {'name': 'JavaScript: The Good Parts', 'pages': 176},
    {'name': 'JavaScript: The Defnitive Guide', 'pages': 1096}
])

collection.sum('pages')

# 1272

你可以可以传递回调自行处理汇总:

collection = Collection([
    {'name': 'Chair', 'colors': ['Black']},
    {'name': 'Desk', 'colors': ['Black', 'Mahogany']},
    {'name': 'Bookcase', 'colors': ['Red', 'Beige', 'Brown']}
])

collection.sum(lambda product: len(product['colors']))

# 6

take()

take方法返回指定传入参数数量元素:

collection = Collection([0, 1, 2, 3, 4, 5])

chunk = collection.take(3)

chunk.all()

# [0, 1, 2]

还可以传入赋值,将会从末端开始计数:

chunk = collection.chunk(-2)

chunk.all()

# [4, 5]

to_json()

to_json方法将集合转换为JSON类型:

collection = Collection([{'name': 'Desk', 'price': 200}])

collection.to_json()

# '[{"name": "Desk", "price": 200}]'

transform()

transform方法对集合迭代,将每个元素作为参数调用指定的回调函数。返回的值会替换原有的值:

collection = Collection([1, 2, 3, 4, 5])

collection.transform(lambda item: item * 2)

collection.all()

# [2, 4, 6, 8, 10]

不像其他集合方法,transform修改集合自身。如果你想生成新的集合,请使用map方法。

unique()

unique方法返回集合中的唯一元素:

collection = Collection([1, 1, 2, 2, 3, 4, 2])

unique = collection.unique()

unique.all()

# [1, 2, 3, 4]

当集合内部为字典或者对象时,可以指定键值来决定唯一性:

collection = Collection([
    {'name': 'iPhone 6', 'brand': 'Apple', 'type': 'phone'},
    {'name': 'iPhone 5', 'brand': 'Apple', 'type': 'phone'},
    {'name': 'Apple Watch', 'brand': 'Apple', 'type': 'watch'},
    {'name': 'Galaxy S6', 'brand': 'Samsung', 'type': 'phone'},
    {'name': 'Galaxy Gear', 'brand': 'Samsung', 'type': 'watch'}
])

unique = collection.unique('brand')

unique.all()

# [
#     {'name': 'iPhone 6', 'brand': 'Apple', 'type': 'phone'},
#     {'name': 'Galaxy S6', 'brand': 'Samsung', 'type': 'phone'}
# ]

还可以传递回调函数,自行决定唯一性:

unique = collection.unique(lambda item: item['brand'] + item['type'])

unique.all()

# [
#     {'name': 'iPhone 6', 'brand': 'Apple', 'type': 'phone'},
#     {'name': 'Apple Watch', 'brand': 'Apple', 'type': 'watch'},
#     {'name': 'Galaxy S6', 'brand': 'Samsung', 'type': 'phone'},
#     {'name': 'Galaxy Gear', 'brand': 'Samsung', 'type': 'watch'}
# ]

where()

where方法通过给定的键值对来过滤集合:

collection = Collection([
    {'name': 'Desk', 'price': 200},
    {'name': 'Chair', 'price': 100},
    {'name': 'Bookcase', 'price': 150},
    {'name': 'Door', 'price': 100},
])

filtered = collection.where('price', 100)

filtered.all()

# [
#     {'name': 'Chair', 'price': 100},
#     {'name': 'Door', 'price': 100}
# ]

zip()

zip方法将集合与给定的列表合并成键值对:

collection = Collection(['Chair', 'Desk'])

zipped = collection.zip([100, 200])

zipped.all()

# [('Chair', 100), ('Desk', 200)]

本文章首发在 LearnKu.com 网站上。

本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://learnku.com/docs/masonite/2.3/or...

译文地址:https://learnku.com/docs/masonite/2.3/or...

上一篇 下一篇
贡献者:2
讨论数量: 0
发起讨论 只看当前版本


暂无话题~