Sv3n-Sk4
Sv3n-Sk4

Reputation: 25

Iteration each elements of a list to split it based on a condition - Python

I have this list :

names = ['pipeline-1__YearBuilt',
    'pipeline-1__NumberofBuildings',
    'pipeline-1__NumberofFloors',
    'pipeline-1__PropertyGFATotal',
    'onehotencoder__x0_Low-Rise Multifamily',
    'onehotencoder__x0_Medical Office',
    'onehotencoder__x0_Mixed Use Property',
    'onehotencoder__x0_Office',
    'onehotencoder__x0_Other',
    'onehotencoder__x0_Refrigerated Warehouse',
    'onehotencoder__x5_Yes'
]

I would like to iterate through each elemens of my list to change it (to clean it for a better readability).

I guess I am close but it doesn't work when I try this :

for n in names:
    new = []
    if n.startswith('pipeline-1'):
        n = n.split('__', 1)[-1]
    else:
        n = n.split('__x', 1)[-1]
    new.append(n)

I only get :

new = ['5_Yes']

I want to keep only the last part of my string.

If anyone can help please. Thanks

Upvotes: 0

Views: 67

Answers (4)

FanGoH
FanGoH

Reputation: 31

The problem is that you are starting an empty array for every object in your names array, you should have new = [] outside the for loop

Upvotes: 0

santo
santo

Reputation: 417

[wrong code]

for n in names:
    new = []
    if n.startswith('pipeline-1'):
        n = n.split('__', 1)[-1]
    else:
        n = n.split('__x', 1)[-1]
    new.append(n)

in this way you create a new list called new n times, where n is the names length.

You must do something like this:

new = []
for n in names:

    if n.startswith('pipeline-1'):
        n = n.split('__', 1)[-1]
    else:
        n = n.split('__x', 1)[-1]
    new.append(n)

Upvotes: 2

JLeno46
JLeno46

Reputation: 1269

new = []
for n in names:
    if n.startswith('pipeline-1'):
        n = n.split('__', 1)[-1]
    else:
        n = n.split('__x', 1)[-1]
    new.append(n)

If new is inside your loop each iteration of the loop will reset new to []

Upvotes: 1

Patrik
Patrik

Reputation: 499

I think this will help you:

new = []
for n in names:
    if n.startswith('pipeline-1'):
        n = n.split('__', 1)[-1]
    else:
        n = n.split('__x', 1)[-1]
    new.append(n)

Your array new was overwritten on each loop therefore you see only the last element. Just put it in front of the loop.

Upvotes: 1

Related Questions