需要以这种格式生成随机json数据
list=['20','30','50','1','200']
for n in list :
data=
{
"total_members_present":1000
"count": n
"total_members_now":980
}
.........
它应该继续,直到列表结束。
使用简单的迭代。
实施例:
lst = ['20','30','50','1','200']
result = []
start = 1000
for i in lst:
data = {
"total_members_present":start,
"count": i,
"total_members_now":start - int(i)
}
start = data["total_members_now"]
result.append(data)
print(result)
输出:
[{'count': '20', 'total_members_now': 980, 'total_members_present': 1000},
{'count': '30', 'total_members_now': 950, 'total_members_present': 980},
{'count': '50', 'total_members_now': 900, 'total_members_present': 950},
{'count': '1', 'total_members_now': 899, 'total_members_present': 900},
{'count': '200', 'total_members_now': 699, 'total_members_present': 899}]
直截了当:
请勿将Python保留名称用作变量(list
,dict
等),以避免它们被模糊。
lst = ['20','30','50','1','200']
start_num = 1000
data = []
for n in map(int, lst):
data.append({
"total_members_present": start_num,
"count": n,
"total_members_now": start_num - n
})
start_num -= n
print(data)
输出:
[{'count': 20, 'total_members_now': 980, 'total_members_present': 1000},
{'count': 30, 'total_members_now': 950, 'total_members_present': 980},
{'count': 50, 'total_members_now': 900, 'total_members_present': 950},
{'count': 1, 'total_members_now': 899, 'total_members_present': 900},
{'count': 200, 'total_members_now': 699, 'total_members_present': 899}]
由于所有答案都使用确定性数据生成(此示例暗含但未明确要求),因此我建议使用python标准随机模块,您可以在此处找到该文档:https://docs.python.org/3/library/random.html
或者,如果您想获得更多的乐趣,请使用fakerr模块: