如何获取列表中每个字符串的第一个单词并创建一个新列表。
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])
输出:
[GenX', 'GenX', 'GenX', 'GenX', 'GenX']
答案 0 :(得分:1)
使用list_comprehensions
:
In [1757]: n = [i.split()[0] for i in list1]
In [1758]: n
Out[1758]: ['GenX', 'GenX', 'GenX', 'GenX', 'GenX']
这基本上是指:
In [1754]: n = []
In [1755]: for i in list1:
...: n.append(i.split()[0])
...:
In [1756]: n
Out[1756]: ['GenX', 'GenX', 'GenX', 'GenX', 'GenX']
答案 1 :(得分:0)
使用str.split
,然后使用索引访问元素。在下面的示例中,我使用列表理解
例如:
list1 = ['GenX XE','GenX XM','GenX XT','GenX XMA','GenX XTA']
print([i.split()[0] for i in list1])
输出:
['GenX', 'GenX', 'GenX', 'GenX', 'GenX']
答案 2 :(得分:0)
您可以这样做
In [5]: map(lambda x:x.split()[0],list1)
Out[5]: ['GenX', 'GenX', 'GenX', 'GenX', 'GenX']
答案 3 :(得分: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])
注意:list1 [i] .split()[0]
答案 4 :(得分:-1)
您可以使用正则表达式执行此操作:
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]
要提取特定信息,您可以执行以下操作:
np.array(r)[:,0]
并获取:
array(['GenX', 'GenX', 'GenX', 'GenX', 'GenX'], dtype='<U4')