Home > Back-end >  Split out of range in certain element in a list
Split out of range in certain element in a list

Time:09-21

I want to split data in a python list and take the index number 1, but the format in the list is not the same, some of the element does not need to be split because it has only one element.

a = ['a,b','b,c','d,e','e']

I apply the code:

a.apply(lambda x: x.split(',')[1])

When I run it, a[3] result in out of range error because it has no index 1. (Error message: IndexError: list index out of range)

How do I deal with this? I still want to split the remaining elements, but for the element that can't be split should remain as it is.

CodePudding user response:

You could use re.findall with a list comprehension:

a = ['a,b','b,c','d,e','e']
output = [re.findall(r'^[^,] ', x)[0] for x in a]
print(output)  # ['a', 'b', 'd', 'e']

The logic here is that the regex pattern '^[^,] will capture the first term of the CSV in each list element (including those elements having only one CSV entry).

CodePudding user response:

You can use something like this:

out = [x.split(',')[1] if ',' in x else x for x in a]

Output would be: ['b', 'c', 'e', 'e']

CodePudding user response:

If you want to use apply you can use map like below:

a = ['a,b','b,c','d,e','e']

list(map((lambda x : x.split(',')[1] if ',' in x else x), a))
# ['b', 'c', 'e', 'e']
  • Related