从文本文件中按整数打印排序的城市名称

Print the sorted city names by an integer from a textfile

我有一个文本文件,每行都有一个城市和一个数字,如下所示:

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)]

为使其正常工作,请对您的代码进行少量更改:

Try it online!

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, city4, city5, city1, city2