Search code examples
sortingamazon-dynamodbironpythonrevit-api

Sort list A2 A4 A1 A3 to A1 A2 A3 A4


I have a list which contains items like A2 A4 A1 A3 B1 B3 B4 A5 B2. I would like to sort it into a list that looks like A1 A2 A3 A4 A5 and then B1 B2 B3 B4 etc..

I have build a script (ironpython) which could be a step in the right direction but I have the feeling there could be an easier way. My questions are:

  • How can I sort the zipped list using the items in the list created in e? I haven't found a way to do this yet. In the current state the script only puts the items beginning with an A together, but not in the numeric order A1, A2, A3 etc...
  • Is there another approach to sort the list as described?
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *

#The inputs to this node will be stored as a list in the IN variables.
dataEnteringNode = IN
import re
output = []
n = 0
stramienen = IN[0]
gridcurves = IN[1]
var = True
b = []
c = []
e = []
for x in stramienen:
    def hasNumbers(inputString):
        return any(char.isdigit() for char in inputString)
    if (hasNumbers(stramienen[n])) == var:
        b.append(stramienen[n])
        c.append(gridcurves[n])
        e.append(re.findall('\d+',stramienen[n]))
        
    n=n+1
d=zip(b,c,e)
# take second element for sort
def takeSecond(elem):
    return elem[0][0]

# sort list with key
d.sort(key=takeSecond)

#Assign your output to the OUT variable.
OUT = d

Solution

  • sorted() is used to sort a list in Python

    >>> mylist=["B3","A3","A4","B2","A2","B1","A1"]
    
    >>> sorted(mylist)
    ['A1', 'A2', 'A3', 'A4', 'B1', 'B2', 'B3']
    
    >>> for i in sorted(mylist): print(i)
    ... 
    A1
    A2
    A3
    A4
    B1
    B2
    B3
    >>>
    

    I feel you need to attend few classes in python. Ex:

    -Define method (def myfunction) outside for loop

    -Comparison for boolean data is True or False

    def hasNumbers(inputString):
        return any(char.isdigit() for char in inputString)
    
    for x in stramienen:
     if hasNumbers(stramienen[n])==True:
        b.append(stramienen[n])
        c.append(gridcurves[n])
        e.append(re.findall('\d+',stramienen[n]))
    

    Hope it helps. Good luck.