如何在Swift中将一个数组的元素添加到另一个数组的元素?

huangapple go评论80阅读模式
英文:

How to add elements of an array to another array's element in Swift?

问题

let prices = [11, 22, 12, 32, 1, 5, 26] //这是一些物品初始价格的集合

let increasingAmount = prices.map{($0 * 0.5)} //这个常数存储了初始价格将增加的金额

我想将increasingAmount添加到prices以获取每个物品的新价格:

let prices =           [11,   22, 12, 32, 1,   5,   26]
let increasingAmount = [5.5,  11, 6,  16, 0.5, 2.5, 13]
let newPrices =        [16.5, 33, 18, 48, 1.5, 7.5, 39] //这是我想要实现的期望输出。

我不想采用将乘法值从0.5修改为1.5的方法。

英文:
let prices = [11, 22, 12, 32, 1, 5, 26] //this is a collection of initial prices of some items

let increasingAmount = prices.map{($0 * 0.5)} //this constant stores the amount the initial price will increase 

I would like to add the increasingAmount to prices to get the new price for each item:

let prices =           [11,   22, 12, 32, 1,   5,   26]
let increasingAmount = [5.5,  11, 6,  16, 0.5, 2.5, 13]
let newPrices =        [16.5, 33, 38, 17, 5.5, 7.5, 39] //this is the desired output that i would like to achieve.

I could just modify the multiply value from 0.5 to 1.5 but I don't want that approach.

答案1

得分: 1

你可以利用zip方法,它将返回一个元组对的序列,形式为(prices_i, increasingAmount_i),然后使用map来求和这些元素

let prices = [11.0, 22.0, 12.0, 32.0, 1.0, 5.0, 26.0]
let increasingAmount = [5.5, 11, 6, 16, 0.5, 2.5, 13]
var newPrices: [Double] = zip(prices, increasingAmount).map { $0 + $1 }
// 或更简洁
newPrices = zip(prices, increasingAmount).map(+)

print(newPrices) // [16.5, 33, 38, 17, 5.5, 7.5, 39]

请注意,你必须指定newPrices的类型,因为Swift编译器将prices数组解释为[Int],将increasingAmount解释为[Double],它需要知道你希望newPrices是什么类型。

即使数组的大小不同,这也可以工作,这种情况下,zip将忽略最长数组中的额外元素。

你可以在这里进行实验。

英文:

You can take advantage of the zip method which is going to return a sequence of tuple pairs of kind (prices_i, increasingAmount_i) and then use map to sum the elements

let prices = [11.0, 22.0, 12.0, 32.0, 1.0, 5.0, 26.0]
let increasingAmount = [5.5, 11, 6, 16, 0.5, 2.5, 13]
var newPrices: [Double] = zip(prices, increasingAmount).map { $0 + $1 }
// or shorter
newPrices = zip(prices, increasingAmount).map(+)

print(newPrices) // [16.5, 33, 38, 17, 5.5, 7.5, 39]

Note that you have to specify the type of newPrices because the swift compiler interprets prices array as [Int] and increasingAmount as [Double] and it has to know what you want newPrices to be.

This will work even if the arrays have different sizes, in that case zip will ignore the extra elements in the longest array.

You can play around with this here

huangapple
  • 本文由 发表于 2023年3月4日 05:14:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75631934.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定