简体   繁体   中英

Python Error's when I try to optimize those lines of code

I use python 2.7, I want to reduce and optimize this code lines but I have a problem, could anybody help me please?

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

  1. I want to take only the 4th value from B
  2. Take just the part after hyphen and the space which is sometimes
  3. Bring back to B

Right now I wrote this 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]

When I try to make it shorter at follows I have two errors.

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

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?

Thank you very much in advance.

您可以使用列表理解:

    B=[[B_element[0],B_element[1],B_element[2],B_element[3].split('-',1)[1].lstrip()] for B_element in B]

I'm not seeing the many ways you've tried, but your code does have a handful of missteps. Even after correcting the indentation errors, your first variant iterates over an index which you don't need four times, and strips every entry twice (only using the result the second time). The second version fails firstly because that index isn't the entry and secondly because you're trying to alter a string instead of replacing it.

A=[]
x=[]
for Bi in B:
    Bi3 = Bi[3]
    part = Bi3.split('-',1)[1].lstrip()
    x.append(Bi3)       # Original B[i][3] data
    A.append(part)      # What is this for?
    Bi[3] = part        # replaces B[i][3]

If you actually need performance, it's quite likely a regular expression might extract the part more efficiently than the split/strip combination, since those functions create new strings for each call.

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

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

result is a list, produced by taking element 3 of each item in B, splitting it on the '-' and stripping leading and trailing spaces from element 1 of the split string. The technique I have used is known as a list comprehension .

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

>>> final = []
>>> for b, r in zip(B, result):
...     final.append([b[0], b[1], b[2], r])
...
>>> final
[[0, None, None, 'Um'], [0, None, None, 'MOM']]

Then just replace B with final :

>>> B = final

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM