Python Error's when I try to optimize those lines of code
<p>I use python 2.7, I want to reduce and optimize this code lines but I have a problem, could anybody help me please? </p>

<p>I have this list <code>B = [[0, Act1, XX1, u'P-Um'],.....[0, Act100, ZZ30, u'D- MOM']]</code> </p>

<ol>
<li>I want to take only the 4th value from B </li>
<li>Take just the part after hyphen and the space which is sometimes</li>
<li>Bring back to B</li>
</ol>

<p>Right now I wrote this code </p>

<pre><code>for i in range(len(B)):
        x.append(B[i][3])
        A = [i.split('-',1)[1] for i in x]  
        #A=[u'Um', u' LY', u' NO', ......, u' MOM']               
    for i in range(len(B)):
        A[i].lstrip()
        p = []
        for i in range(len(B)):
            p.append(A[i].lstrip())
        for i in range(len(B)):
            B[i][3] = p[i]
</code></pre>

<p>When I try to make it shorter at follows I have two errors.</p>

<pre><code>#Short version

for i in range(len(B)):
        x.append(B[i][3])
        A = [i.split('-',1)[1], x] #Error:AttributeError: 'int' object has no           attribute 'split'
        B[i][3].append(A[i].lstrip()) #Error:AttributeError: 'unicode' object has no attribute 'append'
</code></pre>

<p>I try many ways to solve the errors but still not working. Could you help please? Do you think is possible to make the top part shorter without errors?</p>

<p>Thank you very much in advance.</p>

<p>You don't have to index the items of B to iterate over them. This may help.</p>

<pre><code>&gt;&gt;&gt; Act1 = XX1 = Act100 = ZZ30 = None # simply to avoid NameError exceptions
&gt;&gt;&gt; B = [[0, Act1, XX1, u'P-Um'],[0, Act100, ZZ30, u'D- MOM']]
&gt;&gt;&gt; result = [b[3].split('-')[1].strip() for b in B]
&gt;&gt;&gt; result
['Um', 'MOM']
</code></pre>

<p><code>result</code> is a list, produced by taking element 3 of each item in B, splitting it on the <code>'-'</code> and stripping leading and trailing spaces from element 1 of the split string. The technique I have used is known as a <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>.</p>

<p>If you then want to replace the fourth elements with these new values, one way to achieve this is as follows.</p>

<pre><code>&gt;&gt;&gt; final = []
&gt;&gt;&gt; for b, r in zip(B, result):
...     final.append([b[0], b[1], b[2], r])
...
&gt;&gt;&gt; final
[[0, None, None, 'Um'], [0, None, None, 'MOM']]
</code></pre>

<p>Then just replace <code>B</code> with <code>final</code>:</p>

<pre><code>&gt;&gt;&gt; B = final
</code></pre>

python