基于定界符的拆分数组

时间:2018-08-21 02:37:45

标签: python

我有一个像这样的numpy数组:

<div class="input">
  <form>
    <input id="input" type="text" placeholder="Enter task to do...">
    <button type="button" id="add_btn">Add</button>
  </form>
</div>
<div class="task_list">
  <ul id="todo">
    <li></li>
  </ul>
</div>

我想要两个数组:

 ['test_a','help_b','apple_c']

 ['test','help','apple']

5 个答案:

答案 0 :(得分:1)

纯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']

答案 1 :(得分:1)

如果是列表。您可以按照轻松进行操作。

result1=[]
result2=[]
for item in input_list:
    r1, r2 = item.split('_')
    result1.append(r1)
    result2.append(r2)

答案 2 :(得分:0)

提供列表:

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

答案 3 :(得分:0)

使用列表理解和棘手的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='<U5')

y = array(['a', 'b', 'c'], dtype='<U5')

答案 4 :(得分:0)

OR:

>>> l=your_numpy_array.tolist()
>>> a,b=[i.split('_')[0] for i in l],[i.split('_')[1] for i in l]
>>> a
['test', 'help', 'apple']
>>> b
['a', 'b', 'c']
>>>