-1

how do i get 1st word of each string in the list and create a new list.

list1 = ['GenX XE','GenX XM','GenX XT','GenX XMA','GenX XTA']

# this is my my list 
n= len(list1)

for i in range(n):
    print (list1[i])

Output:

[GenX', 'GenX', 'GenX', 'GenX', 'GenX']
aydow
  • 3,673
  • 2
  • 23
  • 40
prapul r
  • 23
  • 4
  • `print([i.split()[0] for i in list1])` – Rakesh Dec 04 '18 at 10:48
  • Take a look at `split()` method of strings. – Paritosh Singh Dec 04 '18 at 10:48
  • Maybe this helps, check split(). https://stackoverflow.com/questions/6181763/converting-a-string-to-a-list-of-words – SanRyu Dec 04 '18 at 10:49
  • @rakesh its indentation error: unexpected indent and I didn't understand what u suggested. – prapul r Dec 04 '18 at 10:51
  • Don't use len-based iteration over lists (or other sequences) in Python. It is a strong anti-pattern. Use `for item in sequence` instead. Also don't use use number suffixes for variable names. Try and come up with meaningful names. In this case eg. "input_strings". – deets Dec 04 '18 at 10:51

5 Answers5

1

Use list_comprehensions:

In [1757]: n = [i.split()[0] for i in list1]

In [1758]: n
Out[1758]: ['GenX', 'GenX', 'GenX', 'GenX', 'GenX']

Which basically means this:

In [1754]: n = []

In [1755]: for i in list1:
      ...:     n.append(i.split()[0])
      ...:     

In [1756]: n
Out[1756]: ['GenX', 'GenX', 'GenX', 'GenX', 'GenX']
Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
0

Use str.split and then use index to access the element. In the below example I am using list comprehension

Ex:

list1 = ['GenX XE','GenX XM','GenX XT','GenX XMA','GenX XTA']
print([i.split()[0] for i in list1])

Output:

['GenX', 'GenX', 'GenX', 'GenX', 'GenX']
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

You can do like this,

In [5]: map(lambda x:x.split()[0],list1)
Out[5]: ['GenX', 'GenX', 'GenX', 'GenX', 'GenX']
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
0
list1 = ['GenX XE','GenX XM','GenX XT','GenX XMA','GenX XTA']

# this is my my list 
n= len(list1)

for i in range(n):
     print (list1[i].split()[0])

Note: list1[i].split()[0]

SanRyu
  • 210
  • 1
  • 2
  • 13
-1

You can do this with regex:

import re
import numpy as np
l = ['GenX XE','GenX XM','GenX XT','GenX XMA','GenX XTA']
r = [re.findall('(?i)([A-Z0-9]+)',x) for x in l]

To extract a specific information you can do:

np.array(r)[:,0]

And obtain:

array(['GenX', 'GenX', 'GenX', 'GenX', 'GenX'], dtype='<U4')
B.Gees
  • 1,125
  • 2
  • 11
  • 28