将列表列表与列表进行比较

时间:2017-02-02 06:51:31

标签: python list

我有一个(Python)列表'A',对应于该列表中的许多(但不是所有)元素,我有特定的数字。例如,我有以下列表A

A = [2, 4 ,6, 8 10 ,12]

并且,列表A的条目以粗体显示( 4 8 10 )具有与它们相关联的相应值( 5 25 55 ),而列表A的其他条目( ie < / em> 2,6,12)没有任何与之相关的值。

我能够在Python中为具有与之关联的值的条目创建列表。像

ListofLists = [[4, 5], [8, 25], [10, 55]] 

相关值”(5,25,55)的来源是 ListofLists ,必须将其与列表 A 。如示例中所示,我希望在列表A中找到没有附加任何值的条目(如缺少值),我想解决这个问题。

我想为列表A中没有任何关联值的条目填充零作为值 ,并通过将'ListofLists'与'A'进行比较来填充 ',我想提出一个新的ListofLists,应该阅读

ListofLists_new = [[2, 0], [4, 5], [6, 0], [8, 25], [10, 55], [12, 0]]

6 个答案:

答案 0 :(得分:2)

假设使用dict映射关联值,如:

associated_values = {8: 25, 10: 55, 4: 5}

# you may get this `dict` via. type-casting `ListofLists` to `dict` as:
#     associated_values = dict(ListofLists)

为了创建一个缺少值为0的映射列表,您可以将dict.get(key, 0) list comprehension 表达式一起使用:

>>> my_list = [2, 4, 6, 8, 10, 12]

>>> [[v, associated_values.get(v, 0)] for v in my_list]
[[2, 0], [4, 5], [6, 0], [8, 25], [10, 55], [12, 0]]

答案 1 :(得分:1)

为什么不使用字典,它应该能很好地完成你的工作。

首先,创建一个类似于ListofLists的dict,使用第一个元素作为键,第二个元素作为每个条目的值。

然后使用dict.get(key,default_value)将是一个更优雅的解决方案。 在你的情况下,dict.get(key,0)就足够了。

答案 2 :(得分:1)

If pole(i, j) = "" Then ActiveWorkbook.Sheets(1).Cells(i + totalrows, j).Value = 0 Else ActiveWorkbook.Sheets(1).Cells(i + totalrows, j).Value = CDbl(pole(i, j)) End If 变为ListofLists,然后您可以使用dict。像这样:

dict.get

(我不确定这是不是你想要的)

答案 3 :(得分:1)

考虑关联是在字典中完成的

assoc = {4:5,8:25,10:55}
A = [2,4,8,6,10,12]
lstoflst = []
for i in A:
    if i in assoc.keys():
        lstoflst.append([i,assoc[i]])
    else:
        lstoflst.append([i,0])
print(lstoflst)

答案 4 :(得分:1)

使用dict的所有建议都是正确的。如果你不能使用词典 - 因为这是家庭作业或其他东西 - 这里有一些代码可以做我认为你想要的东西:

#!python3

A = [2, 4, 6, 8, 10, 12]
ListofLists = [[4, 5], [8, 25], [10, 55]]

result = []

for a in A:
    for k,v in ListofLists:
        if a == k:
            result.append([k,v])
            break
    else:
        result.append([a,0])

assert result == [[2, 0], [4, 5], [6, 0], [8, 25], [10, 55], [12, 0]]
print(result)

答案 5 :(得分:1)

您可以使用字典:

A = [2, 4, 6, 8, 10, 12]
ListOfLists = [[4, 5], [8, 25], [10, 55]]
lol_dict = {key:value for key,value in ListOfLists}
out_dict = {key:lol_dict.get(key,0) for key in A}
final_out = [[key,value] for key,value in out_dict.iteritems()]
print final_out

[[2, 0], [4, 5], [6, 0], [8, 25], [10, 55], [12, 0]]