2024-06-27 20:55:29 发布
网友
我有一个这样的函数,可以将用户的文件{a':1,'b':2}打印到一个新文件,如abc.txt文件,但我不知道如何正确添加infile和outfile。有人能帮我吗?如果我想替换for循环使它更简单,我该怎么做呢?你知道吗
def pretty_printing(dict): order_keys = dict.keys() order_keys.sort() for key in order_keys: print key, dict[key]
要将输出写入'example.txt',请从以下内容开始:
'example.txt'
with open('example.txt', 'w') as out_file: out_file.write(' ... whatever you want to write to the file ...\n')
要将已排序的key, dict[key]字符串连接到行中,请执行以下操作:
key, dict[key]
'\n'.join(['%s, %s' % item for item in sorted(dict.items())])
如果这对你来说太复杂了,就这样做:
for (key, value) in sorted(dict.items()): out_file.write('%s %s\n' % (key, value))
综合起来:
def pretty_print(dict): with open('example.txt', 'w') as out_file: for (key, value) in sorted(dict.items()): out_file.write('%s %s\n' % (key, value)) h = { 'a': 1, 'b': 2 } pretty_print(h)
要将输出写入
'example.txt'
,请从以下内容开始:要将已排序的
key, dict[key]
字符串连接到行中,请执行以下操作:如果这对你来说太复杂了,就这样做:
综合起来:
相关问题 更多 >
编程相关推荐