【问题标题】:How to make two lists reference each other? [closed]如何使两个列表相互引用? [关闭]
【发布时间】:2021-02-19 14:03:15
【问题描述】:

我目前有这样的事情:

x = [['Bob', 'Mary', 'Mary', 'John'], [10, 20, 22, 19]]

如何将 Bob 链接到 10,将 Mary 链接到 20 和 22,将 John 链接到 19?我正在尝试将它们的总数相加,这样会导致:

Bob: 10
Mary: 42
John: 19

【问题讨论】:

  • 请用您尝试过的代码更新您的问题。
  • 它们已经通过各自子列表中的公共索引链接。
  • 压缩列表并使用 collections.Counter
  • 请从intro tour 重复on topic 和how to ask。 Stack Overflow 并不打算取代现有的教程和文档。您需要定义“链接”;如果您只是想要 any 类型的对应关系,那么您需要完成有关基本 Python 数据结构和访问方法的教程。 zip 或 dict 可能是你想要的,但你没有很好地解释你的用例。
  • 如果标识符是字符串变量,则代码是有效的 python。但是,是的,OP 可能忘记了引号

标签: python list reference


【解决方案1】:

您可以使用defaultdict 来累积每个名称的值:

from collections import defaultdict

x = [["Bob", "Mary", "Mary", "John"], [10, 20, 22, 19]]

totals = defaultdict(int)
for name, value in zip(x[0], x[1]):
    totals[name] += value

print(totals)  
# defaultdict(<type 'int'>, {'Bob': 10, 'John': 19, 'Mary': 42})

print(f'Bob: {totals["Bob"]} Mary: {totals["Mary"]} John: {totals["John"]}') 
# Bob: 10 Mary: 42 John: 19

print(" ".join([f"{name}: {value}" for name, value in totals.items()])) # print dynamically all pairs
# Bob: 10 Mary: 42 John: 19

【讨论】:

    【解决方案2】:

    压缩子列表并使用循环按键计数/收集元素:

    import collections
    
    x = [["Bob", "Mary", "Mary", "John"], [10, 20, 22, 19]]
    
    result = collections.Counter()
    for k,v in zip(*x):
        result[k] += v
    
    print(result)
    

    打印:

    Counter({'Mary': 42, 'John': 19, 'Bob': 10})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-04
      • 2016-08-13
      • 2016-10-25
      • 2017-02-22
      • 2022-06-28
      • 2020-06-30
      • 2023-01-07
      相关资源
      最近更新 更多