Reputation: 63
I have devices.txt file that looks like this:
tw004:Galaxy S5:Samsung:Mobilni telefon:5
tw002:Galaxy S6:Samsung:Mobilni telefon:1
tw001:Huawei P8:Huawei:Mobilni telefon:4
tw003:Huawei P9:Huawei:Mobilni telefon:3
Now, I have code like this, and I have to chose how to sort devices in table (for example sort them by code from tw001 to tw004 or sort them by producer's name from A to Z)
def formatheader():
print(
"Code | Name | Producer | Description | Quantity |\n"
"-----+------------+------------+-------------------------+-------------|")
def sortbycode():
devices = open('devices.txt', 'r')
formatheader()
for i in devices:
devices = i.strip("\n").split(":")
print("{0:5}|{1:13}|{2:15}|{3:18}|{4:5}".format(
devices[0],
devices[1],
devices[2],
devices[3],
devices[4]))
print()
How to do that?
Upvotes: 0
Views: 4373
Reputation: 1231
try this.
def formatheader():
print(
"Code | Name | Producer | Description | Quantity |\n"
"-----+-------------+---------------+------------------+-------------|")
def sortbycode():
device_file = open('devices.txt', 'r')
formatheader()
devices = []
for line in device_file:
devices.append([i for i in line.strip("\n").split(":")])
devices.sort(key=lambda x:x[0])
for device in devices:
print("{0:5}|{1:13}|{2:15}|{3:18}|{4:5}".format(*device))
sortbycode()
Upvotes: 1
Reputation:
You can use the .sort
method of lists:
devices.sort()
# or if you want to sort by another field, use a key function
devices.sort(key=lambda x:int(x[4])) # sort by integer value of quantity
You should use a different variable name in the for
loop to avoid messing with devices
. And, if you want to sort by another column, you will need to do the splitting each line of devices
into a list before you loop over and print them. You may need two loops (the original for loop to print, and a while loop to process each line ready to sort)
Side note: for this use case, using .strip()
without any arguments would be safer, as that will catch leading/trailing whitespace, as well as removing '\r\n'
style line endings (if the file so happens to have them).
Also, since you know the list for each row will always be the same format, you could use .format(*devices)
to unpack the list to arguments, which may be shorter or neater.
Upvotes: 0