'I need to sort hundreds of information with their prices using Python 3(VS Code) but they come from a txt document and not too similar to each other
- Red Shoes / 8444 0.016 Children Shoes | For Winter and Spring | $0.016 100 1000000
- Blue Shoes / 8458 0.021 Children Shoes | For Winter and Spring | 0.021 100 1000000
- Blue Shirt / 8420 0.038 Children and Teenager Shirts | For Winter and Spring | $0.038 100 1000000
- Gray Boots / 8423 0.014 Children and Teenager Boots | Suitable For Winter | 0.014 100 1000000
- Pink Sweater / 8431 0.030 Female Children Sweater | Winter and Spring | 0.030 100 1000000
Greetings everyone. A novice coder here. I need to complete this project, and I have hundreds of information like these in a txt file. I tried literally everything I could but couldn't sort them properly. The bold text are price tags, and I need to sort them with price.
f = open("trial1.txt")
list1= []
tuple1=()
for l in f:
a = l.split(" ")
list1.append(a)
tuple1 = tuple(list1)
c = tuple1[1][1]
# print(c.split(" "))
c = sorted(tuple1, key = lambda tuple1: tuple1[1])
print(c)
g = []
h=()
for l in c:
print(l)
l2 = l[4].split(" ")
print(l2[0])
g.append(l2[0])
h = tuple(g)
j = sorted(g, key = lambda g: g[0])
print(j)
I'm stuck here, I could have sorted the prices but only prices. I'm at a serious confusion point. Any help or suggestion is much appreciated.
Edit: I also tried numpy to sort arrays, but that didn't work out for me either. I know I'm doing something wrong but can't figure out what.
Solution 1:[1]
- solved
It worked great so far but I was stuck here. This one was not working properly, they did not get sorted by price at first because they were all strings. Solution below. ps: Below list was in test1.txt
MathBooks / 877 102.30 ?
Novels / 2424 104.5244
RedShoes / 4130 130.00
BlueShoes / 3894 131.00
Notebooks / 1162 147.68
Comics / 4636 150.00
BlackSweater / 2826 16.00
Mug / 3027 16.00
CoffeeMug / 1164 187.319
BlackMug / 6626 20.75
RedShirt / 1179 24.363
BlueShirt / 2423 28.674
ModernMug / 2288 390.00
ModernShoes / 832 47.50
SportShoes / 4133 53.94
BookDesk / 690 55.00 ?
EnglishBooks / 2326 64.7584
BlueBag / 2555 66.13 ?
Backpack / 2314 68.7586
BlackBackpack / 5156 82.44
GrayBackpack / 4132 83.70
GreenMug / 3267 84.45
GrayMug / 4635 90.66
RedMug / 4655 94.25
f = open("test1.txt") s= f.read() lines = [[*line.split(" ")] for line in s.split('\n')] res = sorted(lines, key=lambda line: line[3]) print(res) s = "" for line in res: s += " ".join(line) + '\n' print(s) textFile = open("test2.txt","w") data = textFile.write(s) textFile.close()
res = sorted(lines, key=lambda line: line[3]) sorts the lines lexicographic because they are all strings. It needs to as below in order to sort by number:
res = sorted(lines, key=lambda line: float(line[3]))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
