将少数列表合并到字典中

时间:2016-02-14 19:34:49

标签: ios swift

我有3个列表:

a = ["John", "Archie", "Levi"]
b = ["13", "20"]
c = ["m", "m", "m", "m"]

我想将其合并到一个带字典的列表中:

    result = [
{"name": "John", "age": "13", "gender": "m"},
{"name": "Archie", "age": "20", "gender": "m"},
{"name": "Levi", "age": "", "gender": "m"},
{"name": "", "age": "", "gender": "m"},
    ]

4 个答案:

答案 0 :(得分:4)

好的,这是非常正常的计算机科学问题。以下是如何解决问题的概述:

  1. 首先,确定输入和所需的输出。你做到了。
  2. 注意您需要处理的任何边缘案例
  3. 接下来,使用伪代码绘制逻辑流程。
  4. 从伪代码转换为真实代码。
  5. 测试和调试。
  6. 对于第2步,您的数据表明您希望处理每个源数组中具有不同数量元素的情况。看起来你想为每个数组中的所有0个元素创建一个字典,然后是1个元素的字典等等。当你用完一个给定数组的元素时,看起来你想跳过你的那个键。结果字典条目。

    现在伪代码:

    Find the array with the maximum number of elements. Make this your output_count (the number of items in your output array.)
    Create an output array large enough for output_count entries.
    Loop from 0 to output_count - 1.
      create a dictionary variable
        for each input array, if there are enough elements, add a key/value pair 
        for that array's key and the value at the current index. Otherwise skip 
        that key.
      add the new dictionary to the end of your output array.
    

    这应该足以让你入门。现在看看你是否可以将伪代码转换为实际代码,测试并调试它。使用您的实际代码在此处报告,如果您的代码无法运行,请随时寻求帮助。

答案 1 :(得分:3)

试试这样:

let a = ["John", "Archie", "Levi"]
let b = ["13", "20"]
let c = ["m", "m", "m", "m"]


var dicArray:[[String:String]] = []

for index in 0..<max(a.count,b.count,c.count) {
    dicArray.append([:])
    dicArray[index]["name"] = index < a.count ? a[index] : ""
    dicArray[index]["age"] = index < b.count ? b[index] : ""
    dicArray[index]["gender"] = index < c.count ? c[index] : ""
}

dicArray  // [["gender": "m", "age": "13", "name": "John"], ["gender": "m", "age": "20", "name": "Archie"], ["gender": "m", "age": "", "name": "Levi"], ["gender": "m", "age": "", "name": ""]]

答案 2 :(得分:2)

这是我的看法。我首先创建数组,然后使用enumerate()forEach处理每个数组并将它们添加到字典数组中:

let a = ["John", "Archie", "Levi"]
let b = ["13", "20"]
let c = ["m", "m", "m", "m"]

let count = max(a.count, b.count, c.count)

var result = Array(count: count, repeatedValue: ["name":"", "age":"", "gender":""])

a.enumerate().forEach { idx, val in result[idx]["name"] = val }
b.enumerate().forEach { idx, val in result[idx]["age"] = val }
c.enumerate().forEach { idx, val in result[idx]["gender"] = val }

print(result)
  

[[“gender”:“m”,“age”:“13”,“name”:“John”],[“gender”:“m”,“age”:   “20”,“name”:“Archie”],[“gender”:“m”,“age”:“”,“name”:“Levi”],   [“性别”:“m”,“年龄”:“”,“名称”:“”]]

答案 3 :(得分:2)

这应该做的工作

mailService

输出

let maxLength = max(a.count, b.count, c.count)
let paddedA = a + [String](count: maxLength-a.count, repeatedValue: "")
let paddedB = b + [String](count: maxLength-b.count, repeatedValue: "")
let paddedC = c + [String](count: maxLength-c.count, repeatedValue: "")

let res = zip(paddedA, zip(paddedB, paddedC)).map {
    ["name": $0.0, "age": $0.1.0, "gender": $0.1.1]
}