python - Kotlin:从文件加载包含字符串和元组的字典( HashMap )

标签 python android-studio dictionary kotlin hashmap

嘿,程序员们,

我最近从普通的 Python 编程跳到了 Android Studio 中的 Kotlin 编程。

在 python 中,我生成了一些字典,其中包含字符串作为键和元组作为值。这些元组本身包含一个 int、两个字符串和两个 int。想象一下这个简化的字典:

dict = {"key" : (1,"firstString","secondString",2,0),
        "secondKey":(0,"firstString","secondString",4,1)}

现在可怕的部分来了:我想将我的字典导入到 Kotlin 中的普通变量/值中。

因此,我将所有四个字典放入 res 文件夹中的文本文件中。 对我来说,困难在于声明适当数据结构的 val,然后实际将键值对一步步加载到 val 中。 当深入研究其数据结构时,所有 Kotlin 教程似乎都结束了。

我的猜测是否正确,我应该有一个字典本身的 HashMap ,然后有一个元组的(n数组)列表? 当试图声明复杂的结构时甚至陷入困境:

val importedDict: HashMap<String,Array<Integer,String,String,Integer>> = hashMapOf<String,Array<Int,String,String,Int>()

因为 Kotlin 中似乎没有多种类型的有效数据结构。

非常感谢您提供的任何提示。

最佳答案

我相信表示元组的最简单方法是声明 data class ,像这样:

data class TupleData(val id: Int, 
                     val firstString: String, 
                     val secondString: String, 
                     val otherNumber: Int, 
                     val anotherNumber: Int)

然后将您的数据结构声明为 HashMap<String, TupleData> 。请注意,您必须考虑类型( StringString? )的可空性以及它们是否具有不可变引用( valvar ),因为您没有在问题中指定它们。

此外,为了让您的生活更轻松,我相信您可以使用Moshi使用自定义适配器来解析您的字符串,就好像它是直接解析到数据结构中的 JSON 对象一样。 (但请记住这个 other answer )。

您不能声明 ArrayArray<Integer, String, String, Integer>因为它只需要一个名为 T 的通用参数在 kotlin documentation 。如果你想指定一个元组,你必须使用 PairTriple如果数据多于元组中的数据,则声明 data class

<小时/>

编辑:尝试使用您的数据制作一个工作示例后,我注意到它的格式不适合 JSON 解析,因此您可能必须手动解析它们。

如果您仍然想了解如何序列化为 JSON(也许使用 Python 中的 pickle),这就是我实现适配器的方式:

class TupleDataAdapter {
    @ToJson
    fun toJson(tupleData: TupleData) : String {
        val (id, first, second, other, another) = tupleData;
        return "($id, $first, $second, $other, $another)" 
    }

    @FromJson
    fun fromJson(tuple: String) : TupleData {
        if (tuple[0] != '(' || tuple.last() != ')') {
            throw JsonDataException("Wrong format for tuple data: missing '(' or ')'")
        }

        val trimmed = tuple.trimStart('(').trimEnd(')')
        val fields = trimmed.split(',')
        if (fields.size != 5) {
            throw JsonDataException("Wrong format for tuple data: wrong number of fields in tuple")
        }
        return TupleData(fields[0].toInt(), fields[1], fields[2], fields[3].toInt(), fields[4].toInt()) 
    }
}

fun main(args: Array<String>) {

    val dict = File("./dict.txt").readText()

    println(dict)

    val moshi = Moshi.Builder()
        .add(TupleDataAdapter())
        .build()

    val type = Types.newParameterizedType(Map::class.java, String::class.java, TupleData::class.java)   

    val mapAdapter : JsonAdapter<Map<String, TupleData>> = moshi.adapter(type)
    val decoded : Map<String, TupleData>? = mapAdapter.fromJson(dict)

    println(decoded)
}

当我更改文本时,此实现可以正常工作:

{"key" : "(1,firstString,secondString,2,0)","secondKey" : "(0,firstString,secondString,4,1)"}

注意引号中的区别。

关于python - Kotlin:从文件加载包含字符串和元组的字典( HashMap ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60043722/

相关文章:

python - Pandas 条形图没有显示我需要的东西

python - 使用 win32com 在 Outlook 中按对话线程对邮件进行分类/分组?

python - 为什么 `setup.py install`不更新脚本文件?

python - 如何使用字典为单个键赋予多个值?

macos - 如何挂接 OS X 字典

python - 如何使用列表值对字典进行排序?

python - 在 python 中打印 bool 文字的困惑

android-studio - Android Studio HAXM更新问题

java - 在这种情况下如何将元素添加到 ArrayList

android - ButterKnife 不与 Jack 合作?