[英]Convert list of elements into list of tuples to match the structure of another list of tuples
假設我有以下列表
L = [("a0","a1"),("b0",),("b1","a1","b0"),("a0","a1"),("b0",)]
M = ["u0", "u1", "u2", "u3", "u4", "u5", "u6", "u7" , "u8"]
我想將M
的元素分組到元組列表N
中,使得N
具有與L
相同的結構,即
N = [("u0", "u1"), ("u2",), ("u3", "u4", "u5"), ("u6", "u7") , ("u8",)]
或者,更准確地說, [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]
怎么做?
it = iter(M)
其次是
res = [tuple(itertools.islice(it, len(t))) for t in L]
應該做的伎倆
使用 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.