How to split elements of a list?

PythonListSplit

Python Problem Overview


I have a list:

my_list = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847']

How can I delete the \t and everything after to get this result:

['element1', 'element2', 'element3']

Python Solutions


Solution 1 - Python

Something like:

>>> l = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847']
>>> [i.split('\t', 1)[0] for i in l]
['element1', 'element2', 'element3']

Solution 2 - Python

myList = [i.split('\t')[0] for i in myList] 

Solution 3 - Python

Try iterating through each element of the list, then splitting it at the tab character and adding it to a new list.

for i in list:
    newList.append(i.split('\t')[0])

Solution 4 - Python

Do not use list as variable name. You can take a look at the following code too:

clist = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847', 'element5']
clist = [x[:x.index('\t')] if '\t' in x else x for x in clist]

Or in-place editing:

for i,x in enumerate(clist):
    if '\t' in x:
        clist[i] = x[:x.index('\t')]

Solution 5 - Python

Solution with map and lambda expression:

my_list = list(map(lambda x: x.split('\t')[0], my_list))

Solution 6 - Python

I had to split a list for feature extraction in two parts lt,lc:

ltexts = ((df4.ix[0:,[3,7]]).values).tolist()
random.shuffle(ltexts)

featsets = [(act_features((lt)),lc)               for lc, lt in ltexts]

def act_features(atext):
  features = {}
  for word in nltk.word_tokenize(atext):
     features['cont({})'.format(word.lower())]=True
  return features

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser808545View Question on Stackoverflow
Solution 1 - PythonRoman BodnarchukView Answer on Stackoverflow
Solution 2 - PythondaveView Answer on Stackoverflow
Solution 3 - PythoncaltangeloView Answer on Stackoverflow
Solution 4 - PythonArtsiom RudzenkaView Answer on Stackoverflow
Solution 5 - PythonLukasView Answer on Stackoverflow
Solution 6 - PythonMax KleinerView Answer on Stackoverflow