I want to sort content of a .txt file that is read into Python from its highest to lowest numeric value.
Using the following code:
with open("externalFile.txt", "r") as file:
content = file.read()
print(content)
list = content.splitlines()
def f(text):
return int(text) if text.isdigit() else text
def f1(text):
return [ func(z) for z in re.split('(\d+)', text) ]
list.sort(key=f1)
creates a list and within that list it sorts the content both alphabetically and numerically, as shown below.
However, I only want the content to be sorted numerically in Python, please see below.
How about this:
def f1(text):
name, _, num = text.partition(':')
return int(num)
with open("sorting.txt", "r") as file:
l = file.read().splitlines()
l.sort(key=f1, reverse=True)
print(l)
If you only want to sort numerically, you can use list comprehension,
with open("d:/data.txt") as file:
read_as_lit = [line.strip().split(":") for line in file]
sorted_file = sorted(read_as_lit, key=lambda y:int(y[1]), reverse=True)
print(sorted_file)
[['alpha', ' 50'], ['gamma', ' 45'], ['beta', ' 30'], ['alpha', ' 20'], ['gamma', ' 10'], ['alpha', ' 10']]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.