{'00': ['000011110000111111110000',
'000011110000111111110000',
'000011110000111111110000',
'000010000000111000000000',
'111110000111111000000111',
'111110000111111000000111',
'111110000111111000000111',
'111001111111111000000111',
'000001110000000000000111',
'000011110000000011111111',
'000011110000000011111111',
'000011110000000011111111',
'111111110000000011110000',
'111111110000000011110000',
'111111110000000011110000',
'111000000000000010000000',
'111000000111111110000111',
'111000000111111110000111',
'111000000111111110000111',
'111000000111111001111111',
'000000000111000001110000',
'000011111111000011110000',
'000011111111000011110000',
'000011111111000011110000'],
'01': ['01111111000000',
'01111111000000',
'01111111000000',
'01110000000000',
'01110000000000',
'01110000000000',
'11110000000111',
'11110000000111',
'11110000000111',
'00000000000111',
'00000111111111'],
'02': ['0000111100',
'0000111000',
'1111111001',
'0000000111',
'0000000111',
'0000000111',
'0010000100',
'0001000100',
'0000000100',
'0000000100']}
我有一个看起来像这样的文本文件。我希望输出文件仅从字典中提取值并将它们写入另一个数组中,而且其顺序应与现在出现的顺序相同。因此,应首先显示00数组,然后显示01,02,依此类推。 输出为00-
['000011110000111111110000','000011110000111111110000','000011110000111111110000','000010000000111000000000','111110000111111000000111','111110000111111000000111','111110000111111000000111','111001111111111000000111','000001110000000000000111','000011110000000011111111','000011110000000011111111','000011110000000011111111','111111110000000011110000','111111110000000011110000','111111110000000011110000','111000000000000010000000','111000000111111110000111','111000000111111110000111','111000000111111110000111','111000000111111001111111','000000000111000001110000']
01-
的输出['01111111000000','01111111000000','01111111000000','01110000000000', '01110000000000','01110000000000','11110000000111','11110000000111','11110000000111', '00000000000111','00000111111111']
我尝试使用json解决此问题,但显然每个元素都是一个列表,并且不起作用。
答案 0 :(得分:1)
我很惊讶Python的sample.json
模块对您不起作用,因此我将您的输入存储在名为'
的文件中并亲自尝试。
问题是您的json格式未达到Python期望的格式。它使用单引号("
)代替双引号(json
)来分隔字符串。在我的文本编辑器中打开文件并将所有单引号替换为双引号之后,Python3的>>> import json
>>> with open('./sample.json', 'r') as jfile:
j = json.load(jfile)
>>> j['02']
['0000111100', '0000111000', '1111111001', '0000000111', 00000111',
'0000000111', '0010000100', '0001000100', '0000000100', 000000100']
模块对我来说就很好了。这是我的Python Shell会话:
output.json
现在我可以打开输出文件(>>> with open('./output.json', 'w') as outfile:
outfile.write(str(j['01'])) # Remember to convert the list to a string!
198
)并将其列表写入其中。
$ cat output.json
['01111111000000', '01111111000000', '01111111000000', '01110000000000',
'01110000000000', '01110000000000', '11110000000111', '11110000000111',
'11110000000111', '00000000000111', '00000111111111']
退出python shell之后,列表就在它所属的位置:
json
也许您现在想给{{1}}模块一个机会?当然,它的输入有些挑剔。但是,一旦您满意,与手工切片和切块相比,它将使您的数据处理工作变得更加清晰,简单和不易出错。