Python 基于分隔符的拆分数组
我有一个numpy数组,如下所示:Python 基于分隔符的拆分数组,python,Python,我有一个numpy数组,如下所示: ['test_a','help_b','apple_c'] 我想要两个阵列: ['test','help','apple'] 及 纯python解决方案: x = np.array(['test_a','help_b','apple_c']) a, b = zip(*[k.split('_') for k in x.tolist()]) >>> a # can always make this list(a) ('test', '
['test_a','help_b','apple_c']
我想要两个阵列:
['test','help','apple']
及
纯python解决方案:
x = np.array(['test_a','help_b','apple_c'])
a, b = zip(*[k.split('_') for k in x.tolist()])
>>> a # can always make this list(a)
('test', 'help', 'apple')
使用
pandas
>>> pd.DataFrame(pd.Series(x).str.split('_').tolist())
0 1
0 test a
1 help b
2 apple c
以致
>>> df2[0].tolist()
['test', 'help', 'apple']
纯python解决方案:
x = np.array(['test_a','help_b','apple_c'])
a, b = zip(*[k.split('_') for k in x.tolist()])
>>> a # can always make this list(a)
('test', 'help', 'apple')
使用
pandas
>>> pd.DataFrame(pd.Series(x).str.split('_').tolist())
0 1
0 test a
1 help b
2 apple c
以致
>>> df2[0].tolist()
['test', 'help', 'apple']
给出一个列表:
In [11]: xs = ['test_a','help_b','apple_c']
我可以拆分每个元素,然后“解压”(转置)结果:
In [12]: a, b = zip(*map(lambda x: x.split('_'), xs))
这就是我剩下的:
In [13]: a
Out[13]: ('test', 'help', 'apple')
In [14]: b
Out[14]: ('a', 'b', 'c')
给出一个列表:
In [11]: xs = ['test_a','help_b','apple_c']
我可以拆分每个元素,然后“解压”(转置)结果:
In [12]: a, b = zip(*map(lambda x: x.split('_'), xs))
这就是我剩下的:
In [13]: a
Out[13]: ('test', 'help', 'apple')
In [14]: b
Out[14]: ('a', 'b', 'c')
使用列表理解和技巧
numpy
行解包:
a = np.array(['test_a','help_b','apple_c'])
x, y = np.array([x.split('_') for x in a]).T
结果:
x=
array(['test','help','apple'],dtype='使用列表理解和技巧numpy
行解包:
a = np.array(['test_a','help_b','apple_c'])
x, y = np.array([x.split('_') for x in a]).T
结果:
x=array(['test','help','apple'],dtype=',如果它是一个列表的话。您可以像下面那样轻松地完成它
result1=[]
result2=[]
for item in input_list:
r1, r2 = item.split('_')
result1.append(r1)
result2.append(r2)
如果它是一个列表的话。你可以很容易地按照下面的方式来做
result1=[]
result2=[]
for item in input_list:
r1, r2 = item.split('_')
result1.append(r1)
result2.append(r2)
或:
或:
如果你知道如何迭代列表和拆分字符串,你可以组合一个解决方案。如果你知道如何迭代列表和拆分字符串,你可以组合一个解决方案。如果你知道如何迭代列表和拆分字符串,你可以组合一个解决方案。你还可以调用item.split(“”)
每次迭代一次。:)您还可以调用item.split(“'.')
每次迭代一次。:)