将所有值放入字典并创建具有特定格式的字符串 [英] Get all values into dictionary and create a String with a specific format

查看:70
本文介绍了将所有值放入字典并创建具有特定格式的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本结构如下的字典:

I have a dictionary with this structure:

a: [1,2]
b: [3,4]
c: [5,6]

我需要返回具有此结构的字符串.

and I need to return a string with this structure.

a,b,c\n1,3,5\n2,4,6

我解决了字符串的第一部分.但是要获取其余的String.我尝试迭代到字典中,以获取字典中每个键的第一个元素,然后将每个值的其余元素获取到数组中.

I solved the first part of the string. But to get the rest of the String. I try to iterate into my dictionary to get the first elements for each key in my dictionary and then get the rest for each value into the array.

有没有更简单的方法来获得这个?

Is there an easier way to get this?

推荐答案

一旦您知道键的顺序(字母?),就可以使用以下方法:

Once you know what's the order of the keys (alpha ?), you can use this:

let dict: [String: [Int]] = ["a": [1,2], "b": [3, 4], "c": [5, 6]]
let keys = dict.keys.sorted() //Or do whatever you want here to get your target order
var matrix: [[String]] = []
keys.forEach {
    guard let arrayAsInt = dict[$0] else { return }
    let arrayAsString = arrayAsInt.map{ "\($0)" }
    matrix.append( [$0] + arrayAsString)
}
print("Matrix: \(matrix)")
let transposed = matrix.transposed()
print("Transposed Matrix: \(transposed)")
let output = transposed.map { $0.joined(separator: ",")}.joined(separator: "\n")
print(output)

输出:

$>Matrix: [["a", "1", "2"], ["b", "3", "4"], ["c", "5", "6"]]
$>Transposed Matrix: [["a", "b", "c"], ["1", "3", "5"], ["2", "4", "6"]]
$>a,b,c
1,3,5
2,4,6

很明显,"\ n"可能是不可见的,可能是实际的新行

Obvisouly the "\n" might be invisible and be an actual new line

a,b,c
1,3,5
2,4,6

存在

a,b,c\n1,3,5\n2,4,6

其背后的想法是什么?创建一个矩阵并使用转置(在数学运算中用于矩阵,这是对矩阵的基本修改之一).

What's the idea behind that? Create a matrix and use the transpose (it's used in maths with matrix, it's one of the basic modification of a matrix).

首先将[String:[Int]]转换为[[String]],其中每个元素都是键,后跟其值.我在那里将其转换为String,以便以后使用更简单的代码.

First transform the [String: [Int]] into a [[String]], where each element would be key followed by its values. I transformed it there as String for simpler code later.

为什么要这么做?因为 matrix 值很容易从您的初始 dict 中获得.从 dict 获取 transposed 值比较困难(并非不可能),但从 matrix 获取则更容易,并且 transposed 是快速转换为您的格式.
所以我的想法是相反的:从输出中获取结构,然后如何获取它,它是转置的,所以我需要获取初始输入,依此类推.

Why doing that? Because the matrix value is easy to get from your initial dict. the transposed value is harder (not impossible) to get from dict but easier from matrix, and the transposed is quickly transformed into your format.
So my thinking was the reverse: Get a structure from your output, then how to get it, it's a transpose, so I need to get the initial input as it, etc.

借助于转置矩阵(接受String元素)的代码.

With the help of a code for Transpose Matrix (that accept String elements).

extension Collection where Self.Iterator.Element: RandomAccessCollection {
    // PRECONDITION: `self` must be rectangular, i.e. every row has equal size.
    func transposed() -> [[Self.Iterator.Element.Iterator.Element]] {
        guard let firstRow = self.first else { return [] }
        return firstRow.indices.map { index in
            self.map{ $0[index] }
        }
    }
}

任何技巧(各种各样的)都可以使用.我从这里拿走了.

Any code (there a various) working ones, should the trick. I took it from here.

As pointed by @Leo Dabus, you can remove the Self.Iterator.Element from the extension code (twice). I just wanted to it as such, not modifying the initial answer since it's not mind.

这篇关于将所有值放入字典并创建具有特定格式的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆