簡體   English   中英

正確處理數組的json-string

[英]Handle json-string with array properly

我想找到一種處理json的方法-包含Python中數組的輸入。 我有以下內容:

import json

def main():
    jsonString = '{"matrix":[["1","2"],["3","4"]]}'
    jsonMatrix = json.loads(jsonString)
    Matrix = jsonMatrix["matrix"]
    term1 = Matrix[0][0]       # yields: '1'   expected: 1
    term2 = Matrix[0][1]       # yields: '2'   expected: 2

    result = term1 + term2     # yields: '12'   expected: 3
    return

if __name__ == "__main__":
    main()

到目前為止,我已經找到了“ json.loads”來將json轉換成python對象。 但是,數字仍表示為字符串。 當然,我可以進行以下轉換之一:

Matrix = map(int, Matrix[0])
term1 = Matrix[0]
term2 = Matrix[1]

要么

term1 = map(int, Matrix[0][0])
term2 = map(int, Matrix[0][1])

但是,我正在尋找一種將整個 “ Matrix”對象轉換為int的簡便方法,而不僅僅是將Matrix [0]或Matrix [0] [0]轉換為int。 所以我正在尋找以下的正確版本:

Matrix = map(int, Matrix)
term1 = Matrix[0][0]
term2 = Matrix[0][1]

result = term1 + term2 

我知道我可以使用for循環進行此轉換,但是我想有一種使用更高效代碼的更好方法嗎?

謝謝你的幫助!

import json

def main():
    jsonString = '{"matrix":[["1","2"],["3","4"]]}'
    jsonMatrix = json.loads(jsonString)
    # convert entire matrix to integers
    Matrix = [[int(v) for v in row] for row in jsonMatrix["matrix"]]
    term1 = Matrix[0][0]       # yields: 1
    term2 = Matrix[0][1]       # yields: 2

    result = term1 + term2
    print('result: {}'.format(result))  # -> result: 3
    return

if __name__ == "__main__":
    main()

很基本,很抱歉,但是您可以通過以下任何一種方法將字符串轉換為整數。

new=map(int,Matrix[0])
term1=new[0]       
term2=new[1]       

將字符串轉換為數字,然后使用它們

term1=int(Matrix[0][0])
term2=int(Matrix[0][1])

您還可以執行以下操作:

j=[map(int, y) for y in Matrix]
term1=j[0][0]
term2=j[0][1]

我希望這有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM