0

I am trying to use a list of strings, some of which are repeated. But I can't seem to get the right level of string nesting I need.

I am still a novice in Python, and I am confused. I read this answer and attempted to implement it, but are lists of strings somehow a special case that behave differently than lists of other types?

If I run:

old_freestream_headings='area,MM static pressure,MM relative mach number,'
old_integral_headings='dp,Impulse:0,Impulse:1,Impulse:2,'
old_forces_headings=('pressure force vector:0,pressure force vector:1,pressure force vector:2,'
                     'viscous force vector:0,viscous force vector:1,viscous force vector:2,')                           
old_headings=[old_freestream_headings*2,old_integral_headings,old_forces_headings*5]
print(filter(None,old_headings[0].split(',')))

I get as a result:

['area', 'MM static pressure', 'MM relative mach number', 'area', 'MM static pressure', 'MM relative mach number']

which is both copies of the first string.

If instead I run:

old_freestream_headings='area,MM static pressure,MM relative mach number,'
old_integral_headings='dp,Impulse:0,Impulse:1,Impulse:2,'
old_forces_headings=('pressure force vector:0,pressure force vector:1,pressure force vector:2,'
                     'viscous force vector:0,viscous force vector:1,viscous force  vector:2,')                           
old_headings=[[old_freestream_headings]*2,old_integral_headings,[old_forces_headings]*5]
print(filter(None,old_headings[0].split(',')))

I get an error:

AttributeError: 'list' object has no attribute 'split'

because I am not splitting a string anymore, as old_headings[0] is now a list of two strings.

The output I would like to get is

['area', 'MM static pressure', 'MM relative mach number']

that is, apply split to only one copy of the string.

What am I doing wrong?

Community
  • 1
  • 1
moink
  • 798
  • 8
  • 20
  • *but are lists of strings somehow a special case that behave differently than lists of other types?* nope – Tim Nov 12 '14 at 10:34
  • `[old_freestream_headings]` with this you are wrapping the list inside a new list, is that intentional? – Tim Nov 12 '14 at 10:37
  • why not just `old_freestream_headings.split(',')`? or use `old_headings[0].split(",",3)[0:3]`? – Padraic Cunningham Nov 12 '14 at 10:39
  • @Padraic, I was trying to make a minimal example. These code snippets are part of a larger program, and the creation of the list old_headings happens in one scope and the splitting in another. And the list is not guaranteed to always be three elements long. – moink Nov 12 '14 at 11:33

1 Answers1

1

I think you mean to add lists together

old_headings = [old_freestream_headings] * 2 + [old_integral_headings] + [old_forces_headings] * 5 
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • Thank you! This seems silly that I didn't get it before, but this is exactly what I was trying to do. – moink Nov 12 '14 at 11:31