Swift:Array中元素的出现次数百分比?

时间:2016-07-12 22:48:46

标签: arrays swift dictionary

我有一个变化的数组,我想找到一个元素的出现次数,但表示为百分比,例如:

var filteredArray = [1,2,4,5,2,1,2,1,5,5]

  var counts:[Int: Int] = [:]

  for item in zeroRemovedArray2 {
    counts[item] = (counts[item] ?? 0) + 1
  }

这给出了事件[1:3,2:3,3:0,4:1,5:3]  但是我想要一本[1:0.3,2:0.3,3:0,4:0.1,5:0.3]的字典

我可以看到在某个循环中使用每个值的/.count但是无法弄明白。

1 个答案:

答案 0 :(得分:5)

也许是这样的?

var filteredArray = [1,2,4,5,2,1,2,1,5,5]

var counts:[Int: Double] = [:]

for item in filteredArray {
  counts[item] = (counts[item] ?? 0) + (1.0/Double(filteredArray.count))
}

print(counts)

// Output:
// [5: 0.30000000000000004, 2: 0.30000000000000004, 4: 0.10000000000000001, 1: 0.30000000000000004]