Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

python - Print the sorted city names by an integer from a textfile

I have a textfile that has a city and a number on each line like this:

city1 15
city2 25
city3 2
city4 8
city5 10

I want to print the cities in order from the lowest number to the hights

The print should look like:

city3, city4, city5, city1, city2  

Tried this:

lst = []
with open('livrari.txt', mode='r') as my_file:
    for line in my_file:
       lst.append(line.strip())
lst.sort()

print(lst)

This gives me a list of lists containing the city and the number. Can someone help me finish this?

question from:https://stackoverflow.com/questions/65938532/print-the-sorted-city-names-by-an-integer-from-a-textfile

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use a lambda that sorts your data based on the number in the second column.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...