简体   繁体   中英

How to exchange tuple elements with list elements?

I have a problem regarding tuples and lists in Python:

Suppose I have tuples of the following form

lambda21 = ((0,1),(0,),(),(0))
lambda22 = ((0,),(1,),(0,),(1,))

Now, I have four lists namely

 u1 = [p,r,t]
 l1 = [q,s,u]
 u2 = [v,x]
 l2 = [w,y]

Now, I want to convert my tuple elements into the elements of the lists, where u1 corresponds to lambda21[0], l1 to lambda21[1], u2 to lambda21[2] and l2 to lambda21[3].

And the number in each lambda is the position of the element in the lists and should be exchanged against that element, where the result should be

lambda21 = ((p,r),(q,),(),(w))
lambda22 = ((p,),(s,),(v,),(y,))

Does any one know how to do such an exchange maybe using list-comprehension?

Try this:

lists = [u1, l1, u2, l2]
lambda21 = tuple(tuple(lists[n][index] for index in t) for n, t in enumerate(lambda21))

Tell me if this works because I can't test it right now.

Brought in numpy since you can index with a list on arrays (but not lists).

lambda21 = ((0,1),(0,),(),(0,))
lambda22 = ((0,),(1,),(0,),(1,))

u1 = ['p','r','t']
l1 = ['q','s','u']
u2 = ['v','x']
l2 = ['w','y']

lists = [u1, l1, u2, l2]
[np.array(x)[list(y)] for x, y in zip(lists, lambda21)]

Without numpy you can use another comprehension, may or may not be easier to read:

[[x[t] for t in y] for x, y in zip(lists, lambda21)]

Output:

[['p', 'r'], ['q'], [], ['w']]

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