【问题标题】:How would I append/merge/pair values of the same index or key and ignore values that don't have a matching index or key?我将如何附加/合并/对相同索引或键的值并忽略没有匹配索引或键的值?
【发布时间】:2019-05-28 04:37:02
【问题描述】:

我正在尝试将来自同一索引或键值对的两个列表中的列表值配对/合并在一起。如果该值没有键,则不应配对,如果确实有键,则应配对。

我尝试使用它们的索引附加值,但是,它返回一个 IndexError: list index out of range。我已经使用他们的密钥将它们配对,但输出不是我想要的输出

list1 = [[0, 1], [1, 2], [3, 1]]
list2 = ["append", "values", "to", "one", "another"]

#my attempt at pairing the lists together 
merger = dict(zip(list1, list2))
print(merger)

#converted the first value of the values in list 1 to a key
getKey = {words[0]:words[1:] for words in list1}

#OrderedDict() method to append the two lists
newDict = OrderedDict()
for i, v in enumerate(list2): 
    newDict.setdefault(v, []).append(getKey[i])
print(newDict)

输出

>>> merger output: 
{'append': [0, 1], 'values': [1, 2], 'to':[3, 1]}

>>> expected merger output: 
{'append': [0, 1], 'values':[1, 2], 'one':[3, 1]}

>>> newDict output: 
    IndexError: list index out of range

>>> newDict expected output:
    OrderDict([('append', [[0,1]]), ('values', [[1,2]]), ('one', [[3,1]])]

我在这里想要实现的是 list1 当且仅当它匹配键时附加到 list2 ,否则它不应该输出任何东西。

我不确定如何解决这个问题。提前致谢

【问题讨论】:

  • 1.我建议阅读有关不同功能的 Python 文档(例如 docs.python.org/3.3/library/functions.html#zip),它将解释为什么您没有得到预期的输出。列表迭代也是如此。 2.考虑把你的问题写得更清楚,你问的不是很清楚
  • 显然'to' 不是预期输出中的关键。目前尚不清楚为什么不这样做。这可能与以“...当且仅当 it 匹配键”结尾的规则有关。但不清楚这句话中的“它”指的是什么。

标签: python list indexing ordereddictionary


【解决方案1】:

如果我理解正确,你可以这样做:

list1 = [[0, 1], [1, 2], [3, 1]]
list2 = ["append", "values", "to", "one", "another"]

# create lookup tables (index, values)
lookup1 = {k : [k, v] for k, v in list1}
lookup2 = {i : v for i, v in enumerate(list2)}

merge = {lookup2[k] : v  for k, v in lookup1.items()}

print(merge)

输出

{'append': [0, 1], 'one': [3, 1], 'values': [1, 2]}

请注意,此解决方案假定list1 中子列表的第一个值对应于索引。

【讨论】:

    猜你喜欢
    • 2018-09-02
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    相关资源
    最近更新 更多