【问题标题】:Create a file in python在python中创建一个文件
【发布时间】:2012-11-21 15:30:58
【问题描述】:

现在我知道如何通过文件 txt 实现字典。 所以我创建了 example.txt(通用文件):

aaa.12
bbb.14
ccc.10

并制作字典:

with open('example.text') as f:
    hash = {}
    for line in f:
        key, value = line.strip().split('.', 1)
        hash[key] = int(value)

所以现在我想按价值订购我的元素:所以我尝试

with open('example.txt') as f:
    hash = {}
    for line in f:
        key, value = line.strip().split('.', 1)
        hash[key] = int(value)
        print hash #this print my dict
        value_sort=sorted(hash.values())
        print value:sort #to check the what return and gave me in this case value_sort=[10, 12, 14]

完美,所以现在我如何在 example.txt 上写我的项目按价值排序:

ccc.10
aaa.12
bbb.14

【问题讨论】:

  • 只是好奇,为什么对这个问题投反对票?
  • 也许反对者认为您应该使用适当的序列化程序而不是自己发明。你可以使用pickle或json。
  • 也许 - 由于语法不佳 - 投票者无法理解所要求的内容。

标签: python hashtable


【解决方案1】:

您需要单独循环遍历 hash dict,在其中要求对值进行排序:

from operator import itemgetter

hash = {}
with open('example.text') as f:
    for line in f:
        key, value = line.strip().split('.', 1)
        hash[key] = int(value)

for key, value in sorted(hash.items(), key=itemgetter(1)):
    print '{0}.{1}'.format(key, value)

sorted() 调用被赋予一个排序依据,即每个 .items() 元组(键值对)的第二个元素。

如果您想写入已排序的项目到一个文件,您需要以写入模式打开该文件:

with open('example.txt', 'w') as f:
    for key, value in sorted(hash.items(), key=itemgetter(1)):
        f.write('{0}.{1}\n'.format(key, value))

请注意,我们在每个条目后写换行符 (\n); print 为我们包含一个换行符,但在写入文件时您需要手动包含它。

【讨论】:

  • Martijn,我认为 OP 想要将排序的项目写入文件,而不是打印它们——不过可能是错误的。
  • @martineau:我认为你可能是对的,最后一句话似乎表明了这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-16
  • 2016-07-21
  • 2013-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多