Home > front end >  How to create a new python list based on index of a recurring element in python List
How to create a new python list based on index of a recurring element in python List

Time:09-17

I am working with a python list which looks like-

['',  'tenantspace', 'SYSCode', 'CodeName', 'AttributeValue2', 'AttrDate', '',  'tenantspace', 'SYSCode', 'CodeName', 'AttributeValue2', 'AttrDate', '',  'tenantspace', 'SYSCode', 'CodeName', 'AttributeValue3', 'AttrDate', '',  'tenantspace', 'SYSCode', 'CodeName', 'AttributeValue4', 'AttrDate']

It is the repletion of below elements (guaranteed) with 'SYSCode' being a fixed value in entire list.

'',  'tenantspace', 'SYSCode', 'CodeName', 'AttributeValue', 'AttrDate'

I am looking to create a new list which would only have below elements in it. Since 'SYSCode' is a fixed value in entire list, I am trying to use it as an index. AttributeValue is guaranteed to be at SYSCode Index 2. How do I retrieve below as another list?

['AttributeValue1','AttributeValue2','AttributeValue3','AttributeValue4']

CodePudding user response:

You can achieve it with list comprehension:

ls = ['',  'tenantspace', 'SYSCode', 'CodeName', 'AttributeValue1', 'AttrDate', '',  'tenantspace', 'SYSCode', 'CodeName', 'AttributeValue2', 'AttrDate', '',  'tenantspace', 'SYSCode', 'CodeName', 'AttributeValue3', 'AttrDate', '',  'tenantspace', 'SYSCode', 'CodeName', 'AttributeValue4', 'AttrDate']

res = [ls[i   2] for i in range(len(ls)) if ls[i] == 'SYSCode']

Result would look like:

['AttributeValue1', 'AttributeValue2', 'AttributeValue3', 'AttributeValue4']
  • Related