简体   繁体   English

将元素列表转换为元组列表以匹配另一个元组列表的结构

[英]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我想将M的元素分组到元组列表N中,使得N具有与L相同的结构,即

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]或者,更准确地说, [len(L[ii]) == len(N[ii]) for ii, t in enumerate(L)]具有所有True元素和M == Q ,其中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使用 for 循环

>>> 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)
    
    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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