在Python中,我可以创建一个这样的重复列表:
>>> [1,2,3]*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
在Swift中有一个简洁的方法吗?
我能做的最好的事情是:
1> var r = [Int]()
r: [Int] = 0 values
2> for i in 1...3 {
3. r += [1,2,3]
4. }
5> print(r)
[1, 2, 3, 1, 2, 3, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
Col*_*aff 13
您可以创建一个2D数组,然后使用flatMap它将其转换为一维数组:
let array = [Int](repeating: [1,2,3], count: 3).flatMap{$0}
Run Code Online (Sandbox Code Playgroud)
这是一个扩展,它添加了一个init方法和一个重复方法,该方法采用一个使得它更清洁的数组:
extension Array {
init(repeating: [Element], count: Int) {
self.init([[Element]](repeating: repeating, count: count).flatMap{$0})
}
func repeated(count: Int) -> [Element] {
return [Element](repeating: self, count: count)
}
}
let array = [1,2,3].repeated(count: 3) // => [1, 2, 3, 1, 2, 3, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
请注意,使用新的初始化程序,如果在不提供预期类型的情况下使用它,则可以获得模糊的方法调用:
let array = Array(repeating: [1,2,3], count: 3) // Error: Ambiguous use of ?init(repeating:count:)?
Run Code Online (Sandbox Code Playgroud)
改为使用:
let array = [Int](repeating: [1,2,3], count: 3) // => [1, 2, 3, 1, 2, 3, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
要么
let array:[Int] = Array(repeating: [1,2,3], count: 3) // => [1, 2, 3, 1, 2, 3, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
您可以使用模运算来计算基本集合的索引,并为此进行函数编程:
let base = [1, 2, 3]
let n = 3 //number of repetitions
let r = (0..<(n*base.count)).map{base[$0%base.count]}
Run Code Online (Sandbox Code Playgroud)
您可以为该运算符创建自定义重载*,该重载接受左侧的数组和右侧的整数。
func * <T>(left: [T], right: Int) -> [T] {
return (0..<(right*left.count)).map{left[$0%left.count]}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像在 python 中一样使用你的函数:
[1, 2, 3] * 3
// will evaluate to [1, 2, 3, 1, 2, 3, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
使用 Swift 5,您可以创建一个Array扩展方法,以便将给定数组的元素重复到一个新数组中。下面的 Playground 示例代码显示了此方法的可能实现:
extension Array {
func repeated(count: Int) -> Array<Element> {
assert(count > 0, "count must be greater than 0")
var result = self
for _ in 0 ..< count - 1 {
result += self
}
return result
}
}
let array = [20, 11, 87]
let newArray = array.repeated(count: 3)
print(newArray) // prints: [20, 11, 87, 20, 11, 87, 20, 11, 87]
Run Code Online (Sandbox Code Playgroud)
如果需要,您还可以创建一个中缀运算符来执行此操作:
infix operator **
extension Array {
func repeated(count: Int) -> Array<Element> {
assert(count > 0, "count must be greater than 0")
var result = self
for _ in 0 ..< count - 1 {
result += self
}
return result
}
static func **(lhs: Array<Element>, rhs: Int) -> Array<Element> {
return lhs.repeated(count: rhs)
}
}
let array = [20, 11, 87]
let newArray = array ** 3
print(newArray) // prints: [20, 11, 87, 20, 11, 87, 20, 11, 87]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5948 次 |
| 最近记录: |