How to sort and keep the integrity of the list?
Question: So I have a minor issue with a script I'm writing. I have a text file that
looks something like:

    
    
    '20 zebra 12 bear'
    

That's just an example, the format is 1 line all items separated by spaces.
The script works to sort them out and do a couple of other things to the
strings but what I can't figure out is how to keep it set the way it is. For
example the above line should sort like this:

    
    
    12
    bear
    20
    zebra
    

I need to keep a number in the number place and a string in a strings place
but they should be sorted alphanumerically. Here is my script so far:

    
    
    #!/usr/bin/python
    
    # Make sure you use the proper modules.
    import sys, string
    
    # This area defines the arguments and returns a usage message should it be used incorrectly.
    try:
      infilename = sys.argv[1]; outfilename = sys.argv[2]
    except:
      print "Usage:",sys.argv[0], "infile outfile"; sys.exit(1)
    
    ifile = open(infilename, 'r') # Opens the input file for reading
    ofile = open(outfilename, 'w') # Opens the output file for writing
    data = ifile.readlines()[0].split() # Reads the lines on the input file
    
    # The items in the list are sorted here and defined by a space.
    sort = sorted(data, key=lambda item: (int(item.partition(' ')[0])
                                       if item[0].isdigit() else float('inf'), item))
    
    # Use this to remove any special characters in the list
    filtered = [s.translate(None, string.punctuation) for s in sort]
    
    
    ofile.write('\n'.join(filtered)) # Writes the final output to file (one on each line)
    
    
    
    ifile.close() # Closes the input file
    ofile.close() # Closes the output file
    

I know it's not the prettiest but I haven't been using Python long so if you
have suggestions on how to make it prettier, I'm all ears. All I really need
is to keep a number a number and a string a string but swap them around to
sort. Thanks for any assistance given.


Answer: What you need to do is to create 3rd list. With 1 for number and 2 for string.

So your example would be

1, 2, 1, 2.

Than you put all numbers in one list, and strings in second. Sort them.

Than you replace each 1 in 3rd string with next number and each 2 with next
string.

It should work perfectly.

