英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论