How to split elements of a list?

I have a list:

my_list = ['element1t0238.94', 'element2t2.3904', 'element3t0139847']

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

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Something like:

>>> l = ['element1t0238.94', 'element2t2.3904', 'element3t0139847']
>>> [i.split('t', 1)[0] for i in l]
['element1', 'element2', 'element3']

Method 2

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

Method 3

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])

Method 4

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

clist = ['element1t0238.94', 'element2t2.3904', 'element3t0139847', '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')]

Method 5

Solution with map and lambda expression:

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

Method 6

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x