gpt4 book ai didi

python - 使用首字母大写对文件中的字典元素进行排序

转载 作者:行者123 更新时间:2023-11-30 22:15:24 24 4
gpt4 key购买 nike

嗨,我正在编写一个程序,从文件中读取字典,然后将第一个字母大写并按字母顺序排序

我正在尝试将字典转换为列表。然后我尝试了 for 循环,但不知何故它不起作用

我的文件包含

banana:123
sweet:32
nutella:23

我的代码:

f = open("test.txt", "r")
lst=[]
for line in f.readlines():
data,price = line.split(":")
lst.append([data, (price)])
f.close()

现在,当我尝试 for 循环获取索引时,它给了我错误

for i in range(lst[0:len(lst)][0]):

它给了我错误:

TypeError: 'list' object cannot be interpreted as an integer

我的问题变得令人困惑...我需要做的主要事情是每行的第一个字母变成大写,并且它们按字母顺序在文件中排序。还请告诉我我在这个 for 循环中做错了什么...我希望索引从 [0] 开始到 len[lst]

最佳答案

对于范围问题只需使用

for i in range(len(lst)):

您提供一个列表而不是整数

使用此排序

from operator import itemgetter
f = open("test.txt", "r")
lst = []
for line in f.readlines():
data, price = line.split(":")
lst.append([data, (price)])
f.close()
lst = sorted(lst, key=itemgetter(1))
print map(lambda x: x[0] + ":" + x[1], map(lambda x: [x[0].capitalize(), x[1]], lst))

.....
.....
and write to the file

关于python - 使用首字母大写对文件中的字典元素进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50315029/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com