簡體   English   中英

如何使 json 解析校驗碼更短或更易讀?

[英]How to make json parsing check code shorter or more readable?

有沒有更簡單或更慣用的方法來寫這個?

def jsonToCsvPart1(fields):
    csvFormat = ''
    fields = json.loads(fields)
    for key in fields.keys() :
        tf = str(fields[key])
        mk = ''
        for idx in tf :
            if idx == '{' or idx == '}' or idx == '[' or idx == ']' :
                continue
            else :
               mk += idx
        csvFormat += (mk + ",")
    yield csvFormat

我不確定宏偉的計划是什么,但你可以用一種可能更快的方式來編寫它:

在這里,假設您正在構建一個字符串:

exclude = set(list('{}[]'))  # note: set is faster than list for membership test
mk = ''.join([idx for idx in tf if idx not in exclude])
# 61 ms on a 1M-char random string
exclude = '{}[]'  # ...but string is even faster, when so short
mk = ''.join([idx for idx in tf if idx not in exclude])
# 38 ms on a 1M-char random string

順便說一句,通過讓大循環(在tf的所有字符上)由內置函數完成,並且只需迭代字符以排除:

mk = tf.replace('{', '').replace('}', '').replace('[', '').replace(']', '')
# 11.8ms on 1M chars

而且更快:

mk = tf.translate({ord(c): None for c in '{}[]'})
# 4.5 ms on 1M chars

設置(如果有人有興趣尋找更快的方法):

tf = ''.join(np.random.choice(list('abcdefghijk{}[]'), size=1_000_000))

對於您的特定目的(和學習),檢查字符串中的特定字符將起作用。 python set檢查成員資格更快。 您可以參考其他人的答案來了解如何做到這一點。 例如。

idxs = '{}[]'
for idx in tf:
    if idx in idxs:
        continue
    else:
        mk += idx

由於沒有示例數據,我找不到更易讀的名稱,所以我保持不變。

您可能可以將這兩個for循環嵌套在一起,以獲得更少的行數,但恕我直言,可讀性較差。

def jsonToCsvPart1(fields):
    csvFormats = []
    for tf in json.loads(fields):
        mk = ''.join(str(idx) for idx in tf if str(idx) not in '{}[]')
        csvFormats.append(mk)
    yield ','.join(csvFormats)

暫無
暫無

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

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