快速清单产品 [英] Swift List Product

查看:66
本文介绍了快速清单产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出Swift中的两个列表:

Given two lists in Swift:

let rows = ["a", "b", "c"]
let cols = ["1", "2", "3"]

是否可以使用列表理解将它们组合以产生以下内容:

Is it possible to combine them using list comprehension to produce the following:

squares = ["a1", "a2", "a3", "b1", "b2", "b3", "c1", "c2", "c3"]

很显然,可以使用"for循环"和类似的构造来完成此操作,但是我专门针对基于列表理解的解决方案.我知道Swift可以做一些列表理解(例如letevens = Array(filter(1 ..< 10){$ 0%2 == 0})),但无法弄清楚它是否可以执行类似于下一部分的操作Haskell:

Obviously, it can be done using a "for loop" and similar constructs, but I'm specifically for a list comprehension based solution. I know Swift can do some list comprehension (e.g. let evens = Array(filter(1..<10) { $0 % 2 == 0 }) ) but can't figure out if it can do something similar to the following piece of Haskell:

let squares = [ r ++ c | r <- rows, c <- cols]

推荐答案

可能的解决方案(现已针对 Swift 2 更新):

A possible solution (now updated for Swift 2):

let rows = ["a", "b", "c"]
let cols = ["1", "2", "3"]

let squares = rows.flatMap {
    row in
    cols.map {
        col in
        row + col
    }
}
print(squares)
// [a1, a2, a3, b1, b2, b3, c1, c2, c3]

内部map()cols数组映射到具有 每个条目前面都有行号.外部flatMap()映射 将rows数组更改为数组数组(每行一个)并将结果展平.

The inner map() maps the cols array to an array with the row number prepended to each entry. The outer flatMap() maps the rows array to an array of arrays (one for each row) and flattens the result.

稍微笼统一点,一个可以定义两个的乘积" 序列为具有所有组合的元组(对)的数组:

Slightly more general, one could define the "product" of two sequences as an array of tuples (pairs) with all combinations:

func product<S : SequenceType, T : SequenceType>(lseq : S, _ rseq : T) -> [(S.Generator.Element, T.Generator.Element)] {
    return lseq.flatMap { left in
        rseq.map { right in
            (left, right)
        }
    }
}

然后将其用作

let squares = product(rows, cols).map(+)

这篇关于快速清单产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆