如何解决按文本文件中的整数打印排序的城市名称
我有一个文本文件,每行都有一个城市和一个数字,如下所示:
city1 15
city2 25
city3 2
city4 8
city5 10
我想按照从最低数字到最高数字的顺序打印城市
打印应该是这样的:
city3,city4,city5,city1,city2
试过这个:
lst = []
with open('livrari.txt',mode='r') as my_file:
for line in my_file:
lst.append(line.strip())
lst.sort()
print(lst)
这给了我一个包含城市和号码的列表。有人能帮我完成这个吗?
解决方法
cities = """city1 15
city2 25
city3 2
city4 8
city5 10"""
d = {}
for city_row in cities.splitlines():
city,num = city_row.split(' ')
d[int(num)] = city
d = dict(sorted(d.items())) # Sort
print([d[k] for k in d])
->
['city3','city4','city5','city1','city2']
,
你快到了。您只需要告诉元组中的 list sorting to make use of a particular value 进行排序,因为一般排序会遍历元组中的每个元素来对它们进行排序。
由于我们正在查看元组的第二个元素,即数字字段,我们将使用它进行排序,如下所示:
lst = []
with open('livrari.txt',mode='r') as my_file:
for line in my_file:
city,number = line.strip().split(' ')
# Note that the number field needs to be converted to an integer since
# having them on string would not reap you the numeric sort
number = int(number)
lst.append((city,number))
# The key argument to the sort method is used to tell the list sort to pick a particular field for sorting in terms of nested structures like this one.
lst.sort(key=lambda x: x[1])
print(lst)
[('city3',2),('city4',8),('city5',10),('city1',15),('city2',25)]
,
以下是为了使其正常工作而对代码进行的最小更改:
lst = []
with open('livrari.txt',mode='r') as my_file:
for line in my_file:
lst.append(line.split())
lst.sort(key = lambda e: int(e[1]))
print(','.join([e[0] for e in lst]))
输出:
city3,city4,city5,city1,city2
对于输入:
city1 15
city2 25
city3 2
city4 8
city5 10
,
您可以使用 lambda
根据第二列中的数字对数据进行排序。
with open('csvfile1.csv') as input:
reader = csv.reader(input,delimiter = " ")
sortedlist = sorted(reader,key=lambda col: int(col[1]),reverse=False)
print(",".join([lst[0] for lst in sortedlist]))
# city3,city2
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。