【问题标题】:Python code to access sub-List by index of first element of that sub-List通过该子列表的第一个元素的索引访问子列表的 Python 代码
【发布时间】:2013-11-05 02:11:11
【问题描述】:

我有 2 个以下格式的列表:

list1 = [[[a, b], 0.2], [[a, c], 0.5], [[a, d], 0.3], [[b, d], 0.1]]
# list1 is sorted by first element of its sublist

list2 = [[a, b], [a, d], [b, d]]
# list2 is sorted

我想要 list1' 的子列表的所有 '第二个元素的总和,对应于 list2

中的每个元素

因此 sum 应该是 0.2 + 0.3 + 0.1 = 0.6

注意:subsets 中的元素始终存在于 list1

我的解决方案:

list11=[]
list12=[] 
for i in list1:
    list11.append(i[0])
    list12.append(i[1])

sum=0

for i in list2:
    sum+=list12[list11.index(i)]

我希望有一个不涉及创建临时列表的解决方案。

【问题讨论】:

    标签: python


    【解决方案1】:

    您可以使用list comprehension 来实现:

    x = [['a', 'b'], ['a', 'd'], ['b', 'd']]
    y = [[['a', 'b'], 0.2], [['a', c], 0.5], [['a', 'd'], 0.3], [['b', 'd'], 0.1]]
    total = sum([b for a, b in y if a in x])
    

    演示

    >>> x = [['a','b'], ['a', 'd'], ['b', 'd']]
    >>> y = [[['a', 'b'], 0.2], [['a', 'c'], 0.5], [['a', 'd'], 0.3], [['b', 'd'], 0.1]]
    >>> [b for a, b in y if a in x]
    [0.2, 0.3, 0.1]
    >>> sum([b for a, b in y if a in x])
    0.6
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-03
      • 2023-01-10
      • 1970-01-01
      • 2021-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多