Swift3循环字典来增加价值

时间:2017-05-09 05:00:56

标签: swift dictionary swift3

我刚接触编程我只是在游乐场玩,我试图在字典中循环进行一些计算并将它们添加到新字典中,但是,我只能添加一个字典值。我不知道为什么。能再告诉我并指出重点吗?

    var name:String?

var popDict: [String: Array<Double>]?
var FinalDict: [String: Array<Double>]?
var mean: Double?
var elementSideArr: Array<Double>?

var nameArray = ["Olivia": [1,2,2,2,1,2,1,0.0001,0,1,2], "Amber": [52,52,65,66,57,63,62,0.0001,0,0,0]]

var doubleArr = [Double]()

for (key, value) in nameArray{

  let thisValue = value
  let arrayS = thisValue.prefix(7)
  let slice = arrayS[0...6]
  let popSideArr = Array(slice)
  let average: Double = (popSideArr as NSArray).value(forKeyPath: "@avg.self") as! Double

      mean = average
  let thatValue = value
  let arraySS = thatValue.suffix(3)
  let sslice = arraySS[8...10]
   elementSideArr = Array(sslice)


  elementSideArr?.insert(average, at: 0)


  let dict = ["\(key)":  elementSideArr!]

  for (key,value) in dict{

    popDict = dict

  }
}
print(popDict!)

[“Olivia”:[1.5714285714285714,0.0,1.0,2.0]] //这是唯一的输出,但它应该是2个项目。

1 个答案:

答案 0 :(得分:0)

问题在于你的内部for循环,你正在将整个新词典初始化为let dict = ["\(key)": elementSideArr!] for (key,value) in dict{ popDict = dict } ,如果你的词典中有单个键和值对,那么你也不需要循环。

替换代码行:

popDict["\(key)"] = elementSideArr!

。通过

average

注意:无需将swift数组转换为NSArray来计算reduce,您只需使用let array = popSideArr as? [Int] ?? [] let res = Double(array.reduce(0, +)) / Double(popSideArr.count) 获取总数,然后将总数除以数组计数。

     def longest_string(seq):
         max_list = max(seq,key=len)
         return max_list
     print(longest_string(["h","el","lo","worl","d"]))
     worl