Generate a list for Transpose Fields tool

776
2
Jump to solution
12-05-2016 12:51 PM
EvaKarau
New Contributor II

I am trying to generate the inputs for arcpy.TransposeFields_management and I am running into a problem with the list that feeds the FieldsToTranspose.  If I run the tool manually, and then save the code as a python snippet, this is how the fields are specified in the snippet:  

in_field="A_4431 4431;A_1111 1111"  

So, I am trying to create a list of my fields that follows that format, but this eludes me. Here is the code I have been working with - see the explanation in the comments for what happens when I run it…  

# Set local variables

InTable = "C:\Distubance\OutTab.gdb\FACTS_Code_2010_1"

# Specify fields to transpose FieldNames = arcpy.ListFields(InTable, "A*")

OrigFieldNames = []

FieldShortNames = []

for f in FieldNames: OrigFieldNames.append(f.name)

FieldShortNames.append(f.name[2:6])

#To generate a list of the old field names and the new, desired field names to use in the Transpose tool, I tried this: FieldsToTranspose = [OrigFieldNames + " " + FieldShortNames for i in xrange(len(OrigFieldNames))] # This generates a nice list, the tool runs and the output table is generated, but that table is empty.  

# Set a variable to store output feature class or table

outTable = "TestTab"

# Set a variable to store code field name

TransposedFieldName = "FCode"

# Set a variable to store value field name

ValueFieldName = "AreaM2"

# Specify attribute field to be included in the output

AttrFields = "ZSID"

# Execute

TransposeFields arcpy.TransposeFields_management(InTable, FieldsToTranspose, outTable, TransposedFieldName, ValueFieldName, AttrFields)  

Anyone have an idea how I can either generate the list with the proper formatting in the first place, or modify the list to follow the correct formatting, after I generate it using the method above?

Thanks much!

1 Solution

Accepted Solutions
DarrenWiens2
MVP Honored Contributor

I think you've already got your list in the format below, just use ';'.join(list) to insert semi-colons in between list items and return the string:

>>> my_list = ['field1a field1b','field2a field2b','field3a field3b','field4a field4b']
... delimited_list = ';'.join(my_list)
... print delimited_list
... 
field1a field1b;field2a field2b;field3a field3b;field4a field4b

View solution in original post

2 Replies
DarrenWiens2
MVP Honored Contributor

I think you've already got your list in the format below, just use ';'.join(list) to insert semi-colons in between list items and return the string:

>>> my_list = ['field1a field1b','field2a field2b','field3a field3b','field4a field4b']
... delimited_list = ';'.join(my_list)
... print delimited_list
... 
field1a field1b;field2a field2b;field3a field3b;field4a field4b
EvaKarau
New Contributor II

Wow. That alone seems to have done the trick! Thanks much, Darren.