如何使json解析检查代码更短或更可读



有没有更简单或更惯用的方法来写这篇文章?

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))

对于您的特定目的(和学习(,检查字符串中的特定字符将起作用。pythonset在检查成员身份方面速度更快。关于如何做到这一点,你可以参考别人的答案。例如

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

由于没有样本数据,我找不到更可读的名称,所以我保持它们不变。

您可能可以将这两个for循环嵌套在一起,以获得更少的行,但可读性较差的IMHO。

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)

最新更新