简体   繁体   中英

Convert list of elements into list of tuples to match the structure of another list of tuples

Say that I have the following lists

L = [("a0","a1"),("b0",),("b1","a1","b0"),("a0","a1"),("b0",)]
M = ["u0", "u1", "u2", "u3", "u4", "u5", "u6", "u7" , "u8"]

and I want to group the elements of M into a list of tuples N such that N has the same structure of L , ie

N = [("u0", "u1"), ("u2",), ("u3", "u4", "u5"), ("u6", "u7") , ("u8",)]

or, to be more precise, such that [len(L[ii]) == len(N[ii]) for ii, t in enumerate(L)] has all True elements and M == Q , where Q = [item for t in N for item in t]

How to do that?

it = iter(M)

followed by

res = [tuple(itertools.islice(it, len(t))) for t in L]

should do the trick

using for loop

>>> L = [("a0","a1"),("b0",),("b1","a1","b0"),("a0","a1"),("b0",)]
>>> M = ["u0", "u1", "u2", "u3", "u4", "u5", "u6", "u7" , "u8"]
>>> R =[]
>>> idx = 0
>>> for i in [len(j) for j in L]:
...     R.append(tuple(M[idx:idx+i]))
...     idx+=i
... 
>>> R
[('u0', 'u1'), ('u2',), ('u3', 'u4', 'u5'), ('u6', 'u7'), ('u8',)]
L = [("a0","a1"),("b0",),("b1","a1","b0"),("a0","a1"),("b0",)]
M = ["u0", "u1", "u2", "u3", "u4", "u5", "u6", "u7" , "u8"]

len_L_elements = []

for i in L:
    len_L_elements.append(len(i))
    
print(len_L_elements)

res = []
c = 0 # It will handle element of M
d = 0 # It will handle element of len_L_elemenst

while c <= len(M)-1 and d <= len(len_L_elements)-1:
    temp_lis = [] # this will convert int tuple on time of append
    cnt = 0 # Initialize with 0 on one tuple creation
    while cnt <= len_L_elements[d]-1:
        temp_lis.append(M[c])
        c+=1
        cnt+=1
    
    # Convert List into tuple
    temp_tuple = tuple(temp_lis)
    res.append(temp_tuple)
    d+=1
print(res)
    
    

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