嵌套的元组列表和分数列表

Nested list of tuples and list of scores

我有问题,我会尽力解释。 我有两个列表,每个列表有 3 个项目。 list1 中的每个项目在 list2 中都有一个分数。

List1= [[(3,4,5)], [(23,44), (23,5,3), (1,2)], [(23,5), (1,6)]]
List2= [2,4,1]

在list1中可以看到,item 2和3有多个对应分数的元组,我想把它们分成分数:

what I want:
List1= [(3,4,5), (23,44), (23,5,3), (1,2), (23,5), (1,6)]
List2= [2,4,4,4,1,1]

or 

List1= [[(3,4,5)], [(23,44)], [(23,5,3)], [(1,2)], [(23,5)], [(1,6)]]
List2= [2,4,4,4,1,1]

到目前为止,我已经确定了需要更改的项目。

double = [x for x in List1 if len(x)>1]
print(double)

[[(23, 44), (23, 5, 3), (1, 2)], [(23, 5), (1, 6)]]

我找到了这些项目的索引:

indx = [i for y in double for i, x in enumerate(List1) if x== y ]
print(indx)

[1, 2]

我已将嵌套列表展平以在 list1 中获得我想要的内容:

flat_list = [item for sublist in List1 for item in sublist]

[(3, 4, 5), (23, 44), (23, 5, 3), (1, 2), (23, 5), (1, 6)]

但是我不确定如何更改 list2。

任何帮助将不胜感激。

谢谢。

我会使用 zip 来串联迭代项目和分数。

List1= [[(3,4,5)], [(23,44), (23,5,3), (1,2)], [(23,5), (1,6)]]
List2= [2,4,1]
new1 = []
new2 = []

# iterate over the list of list of tuples and scores in parallel
for item, score in zip(List1, List2):
    # iterate over the tuples in the list of tuples
    for subitem in item:
        new1.append(subitem)
        new2.append(score)

这可以像下面的一些例子一样写得更简洁,但对于初学者来说,这更容易理解。

一种方法(这些问题往往会引出神秘的单行):

l1, l2 = zip(*((tpl, scr) for tpls, scr in zip(List1, List2) for tpl in tpls))
l1
# ((3, 4, 5), (23, 44), (23, 5, 3), (1, 2), (23, 5), (1, 6))
l2
# (2, 4, 4, 4, 1, 1)

嵌套的生成器表达式生成元组分数对,zip(*...) 模式将它们转置为我们通过多重赋值捕获的两个单独的元组。 如果需要,您可以轻松地将它们转换为列表。

一种更具可读性和初学者友好的方式:

tuples, scores = [], []
for tpls, scr in zip(List1, List2):
    for tpl in tpls:
        tuples.append(tpl)
        scores.append(scr)

tuples
# [(3, 4, 5), (23, 44), (23, 5, 3), (1, 2), (23, 5), (1, 6)]
scores
# [2, 4, 4, 4, 1, 1]

这应该有效:

>>> List1= [[(3,4,5)], [(23,44), (23,5,3), (1,2)], [(23,5), (1,6)]]
>>> List2= [2,4,1]
>>> 
>>> new1 = [w for v in List1 for w in v]
>>> new1
[(3, 4, 5), (23, 44), (23, 5, 3), (1, 2), (23, 5), (1, 6)]
>>> 
>>> new2 = [n for s, n in zip(List1, List2) for i in s]
>>> new2
[2, 4, 4, 4, 1, 1]
>>> 

有列表理解:

List1Modified = [subset for lists in List1 for subset in lists]
List2Modified = [List2[idx] for idx, lists in enumerate(List1) for _ in lists]

print(List1Modified)
print(List2Modified)

>> [(3, 4, 5), (23, 44), (23, 5, 3), (1, 2), (23, 5), (1, 6)]
>> [2, 4, 4, 4, 1, 1]
List1_new=[]
List2_new=[]
for i in range(len(List1)):
    List1_new+=List1[i]
    List2_new+=[List2[i]]*len(List1[i])

试试这个:

List2 =[List2[j] for j, i in enumerate(List1) for k in range(len(i))]

List1 = [j for i in List1 for j in i]

只是一个 hack,用 list comp 构建一个,另一个作为副作用。

l2 = []
l1 = [l2.append(scr) or tpl for tpls, scr in zip(List1, List2) for tpl in tpls]