pythonoperatorsruleslist-manipulation

How to apply rules to python list?


I have a list in the following form

[1, C0, C1, C1*C0, C0**2, C0*C1, C0*C1*C0, B0, B0*C0, B0*C1, B0*C1*C0, B0*C0**2, B0*C0*C1, B0*C0*C1*C0, B1, B1*C0, B1*C1, B1*C1*C0, B1*C0**2, B1*C0*C1, B1*C0*C1*C0, B1*B0, B1*B0*C0, B1*B0*C1, B1*B0*C1*C0, B1*B0*C0**2, B1*B0*C0*C1, B1*B0*C0*C1*C0, B0**2, B0**2*C0, B0**2*C1, B0**2*C1*C0,...]

with A0, A1, B0, B1, C0, C1 being defined as operators from the ncpol2sdpa package. Since those operators are supposed to be unitary and hermitian, they should square to one. In particular they should follow the rule

A0^2 = 1, A1^2 = 1, B0^2 = 1, B1^2 = 1, C0^2 = 1, C1^2 = 1.

Now I would like to apply those rules to all list elements so that the expected outcome would look like the following

[1, C0, C1, C1*C0, 1, C0*C1, C0*C1*C0, B0, B0*C0, B0*C1, B0*C1*C0, B0, B0*C0*C1, B0*C0*C1*C0, B1, B1*C0, B1*C1, B1*C1*C0, B1, B1*C0*C1, B1*C0*C1*C0, B1*B0, B1*B0*C0, B1*B0*C1, B1*B0*C1*C0, B1*B0, B1*B0*C0*C1, B1*B0*C0*C1*C0, C0, C1, C1*C0,...]

My first thought was to convert every element in the list to a string in order to scan all elements for a specific pattern like A0^2, A1^2 etc. and set it to 1. But I was not sure how to transform the string elements back into operator elements and also thought there should probably be a much more elegant solution to set some constraints onto the list elements.


Solution

  • One quick way to do something like this is to write a function that you can use as a filter during list comprehension. Suppose you had a function already written that transforms your string elements (e.g. A0^2 --> 1), then you could convert everything with list compression as: yourlist = [function(x) for x in originallist]

    BUT! if you need to retrieve your operator items afterwards, your best bet is probably to use a dictionary since they can store just about anything. In that case, you'd want to form some new dictionary ={}, and say dictionary[string equivalent] = operator. That way, you could retrieve the operator from a given string.

    Furthermore, you could do this all in one go as: yourlist = [string_to_operator_dict[function(x)] for x in original list]

    IFF you have both 1) function already written and 2) dictionary[string]->operator already populated