0

I am having an issue with my code. I am trying to print out in numerical order the folder's name while taking in information from that folder's Report.csv file.

red = []
black = []
orange = []

for x in dirs:
    if x[0:3] == "red":
        red.append(x)     
    elif x[0:5] == "black":
        black.append(x)
    elif x[0:6] == "orange":
        orange.append(x)

for x in red:
    print(f"{x}:")
    try:
        df = pd.read_csv(x + "/Report.csv")
        df_filter= df[['Start','ID','Name',"Type", "Status", "Info"]]
        testFilter = df_filter[(df_filter.Type == 'Test')]
        if testFilter['Status'].str.contains('Fail').any():
            fullFinalTable= testFilter[['Start','ID','Name', "Info"]]
            print(fullFinalTable)
        else:
            print("No errors.")
    except FileNotFoundError:
        print("File does not exist")

When doing print(f"{x}:") I will get the following output

red1
red10
red11
.
.
.
red19
red2
red20
red21
.
.
.

However, I am trying to make sure it is in numerical order (red1, red2, red3...red10, red11, etc). I have tried to convert x into a float and an integer, however no luck.

Beso
  • 1,176
  • 5
  • 12
  • 26
QueenBee
  • 107
  • 1
  • 9

2 Answers2

1

Please try this

red_order = [int(x.replace('red','')) for x in red]
red_order.sort()
red = ['red'+str(x) for x in red_order]
Mahbubur Rahman
  • 361
  • 2
  • 8
0

So, it looks like you might be better off removing your color prefixes and then just storing the numbers. If you do that, then you can cast to int and then sort numerically.

red = []
for x in dirs:
   if x.startswith('red'): # startswith is just easier to read, for me.
       red.append(int(x[3:])) # store only the number part, and store it as an integer.
                              # That way it will be sorted numerically by `sorted` below.

# Just sorting inline because why not? It looks cleaner to me.
for x in sorted(red):
    full_name = 'red' + str(x)

    print(f"{x}:")

    # Do what you were doing before.

If you need something a bit more verbose, then I would recommend the natsort library. It has a lot of different options which address the less intuitive sorting problems in programming. This is a basic example which addresses your problem directly:

>>> from natsorted import natsorted
>>> a = ['version-1.9', 'version-2.0', 'version-1.11', 'version-1.10']
>>> natsorted(a)
['version-1.9', 'version-1.10', 'version-1.11', 'version-2.0']

And here is their example for humansorted

>>> a = ['Apple', 'Banana', 'apple', 'banana']
>>> natsorted(a)
['Apple', 'Banana', 'apple', 'banana']
>>> humansorted(a)
['apple', 'Apple', 'banana', 'Banana']
cwallenpoole
  • 79,954
  • 26
  • 128
  • 166