Python file line sort

I want the Bubblesort file to be numbered, and I have 2 errors in my code.

File lines contain: string-space-number

The answer is wrong sorting, or sometimes I get an IndexError as well, because x.append (string [l]) is out of range

Hope someone can help me

the code:

#!/usr/bin/python
filename = "Numberfile.txt"
fo = open(filename, "r")

x, y, z, b = [], [], [], []

for line in fo:             # read
   row = line.split(" ")    # split items by space
   x.append(row[1])         # number


liste = fo.readlines()
lines = len(liste)
fo.close()

for passesLeft in range(lines-1, 0, -1):
    for i in range(passesLeft):
        if x[i] > x[i+1]:
                temp = liste[i]
                liste[i] = liste[i+1]
                liste[i+1] = temp

fo = open(filename, "w")
for i in liste:
    fo.writelines("%s" % i)
fo.close()
+4
source share
2 answers

There seems to be empty lines in the file.

Edit:

for line in fo:             # read
   row = line.split(" ")    # split items by space
   x.append(row[1])         # number

with:

for line in fo:             # read
   if line.strip():
       row = line.split(" ")    # split items by space
       x.append(row[1])         # number

By the way, you better use re.split with regex \s+:

re.split(r'\s+', line)

which makes your code more robust - it will be able to handle several spaces as well.

For the second problem, Anand continued me: you compare strings, if you want to compare numbers, you will have to wrap them with a call int()

+1
source

, , , , x - , , , '12' 2 .. x int.

, ListIndex, , , , .

-

for line in fo:
   if line.strip():
       row = line.split(" ")
       x.append(int(row[1]))  
+1

Source: https://habr.com/ru/post/1598064/


All Articles