0

I have this python list:

['Intercept', 'a', 'country[T.BE]', 'country[T.CY]', 'country[T.DE]', 'b', 'c', 'd', 'e']

I want the country items at the end:

['Intercept', 'a', 'b', 'c', 'd', 'e', 'country[T.BE]', 'country[T.CY]', 'country[T.DE]']

How to accomplish this?

(Note, the items are column headers of a dataframe that I will use for regression analysis. The column names and the weird ordering are generated by patsy.dmatrices.)

I tried sorting, pop, del, and list comprehension, but to no avail. In this case I decided not to explain what I did to solve this problem and did not work. It is a simple problem, and unlike one commentators, I do not have decades of programming experience.

Martien Lubberink
  • 2,614
  • 1
  • 19
  • 31

2 Answers2

1

If your logic is to put any item that contains country to the back, use sorted with key:

l = ['Intercept', 'a', 'country[T.BE]', 'country[T.CY]', 'country[T.DE]', 'b', 'c', 'd', 'e']
sorted(l, key=lambda x: 'country' in x)

Output:

['Intercept',
 'a',
 'b',
 'c',
 'd',
 'e',
 'country[T.BE]',
 'country[T.CY]',
 'country[T.DE]']
Chris
  • 29,127
  • 3
  • 28
  • 51
1

Here I assume having or not the country[ text is what you want to split... then you can use:

li = ['Intercept', 'a', 'country[T.BE]', 'country[T.CY]', 'country[T.DE]', 'b', 'c', 'd', 'e']
[x for x in li if not 'country[' in x] + [x for x in li if 'country[' in x]
dmontaner
  • 2,076
  • 1
  • 14
  • 17