gpt4 book ai didi

arrays - 计算数组数组中的项目?

转载 作者:搜寻专家 更新时间:2023-10-30 22:22:05 24 4
gpt4 key购买 nike

如果我有一个声明为

的对象
let compoundArray = [Array<String>]

是否有一个属性可以提供 compoundArray 中包含的所有数组中的字符串数?

我可以通过将每个数组中的所有项目相加来做到这一点:

var totalCount = 0
for array in compoundArray {
totalCount += array.count }
//totalCount = total items in all arrays within compoundArray

但这看起来很笨重,而且 swift 似乎有 Array 的属性/方法来执行此操作,不是吗?

谢谢!

最佳答案

您可以添加嵌套数组计数

let count = compoundArray.reduce(0) { $0 + $1.count }

大型 阵列的性能比较(在发布配置的 MacBook Pro 上编译和运行):

let N = 20_000
let compoundArray = Array(repeating: Array(repeating: "String", count: N), count: N)

do {
let start = Date()
let count = compoundArray.joined().count
let end = Date()
print(end.timeIntervalSince(start))
// 0.729196012020111
}

do {
let start = Date()
let count = compoundArray.flatMap({$0}).count
let end = Date()
print(end.timeIntervalSince(start))
// 29.841913998127
}

do {
let start = Date()
let count = compoundArray.reduce(0) { $0 + $1.count }
let end = Date()
print(end.timeIntervalSince(start))
// 0.000432014465332031
}

关于arrays - 计算数组数组中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41631854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com