【问题标题】:Replace sublist with another sublist - python [closed]用另一个子列表替换子列表 - python [关闭]
【发布时间】:2019-01-04 12:38:15
【问题描述】:

我有一个清单:

Online = [['Robot1', '23.9', 'None', '0'], ['Robot2', '25.9', 'None', '0']]

如果我收到不同的值,我想替换子列表:

NewSublist1 =  ['Robot1', '30.9', 'Sending', '440']

NewSublist2 =  ['Robot2', '50']

我想要:

Online = [['Robot1', '30.9', 'Sending', '440'], ['Robot2', '50']]

子列表元素的数量可能会改变。唯一相同的是机器人 ID。所以我想进行搜索,看看机器人 id 是否在在线列表中,并将子列表替换为新的。

【问题讨论】:

  • 好的,这听起来很简单。你的代码是什么样的,你在哪里卡住了?
  • 您要合并这些列表吗?
  • 请贴出你目前写的代码,并通读Python数据结构教程:docs.python.org/3/tutorial/datastructures.html

标签: python list replace sublist


【解决方案1】:

您可以创建一个字典,将新子列表中的 robot ID 映射到实际的新子列表,然后在该字典中查找现有的 robot ID 并进行相应替换。

>>> Online = [['Robot1', '23.9', 'None', '0'], ['Robot3', 'has no replacement'], ['Robot2', '25.9', 'None', '0']]
>>> NewSublists = [['Robot1', '30.9', 'Sending', '440'], ['Robot2', '50'], ['Robot4', 'new entry']]
>>> newsub_dict = {sub[0]: sub for sub in NewSublists}
>>> [newsub_dict.get(sub[0], sub) for sub in Online]
[['Robot1', '30.9', 'Sending', '440'],
 ['Robot3', 'has no replacement'],
 ['Robot2', '50']]

这将遍历列表中的每个元素一次,使其复杂度为 O(n),n 是 Online 列表中的元素数。相反,如果您将 Online 也作为字典将 robot ID 映射到子列表,则可以将其降低到 O(k),k 是新子列表的数量。

如果您还想添加从 NewSublistsOnline 的元素(如果这些元素尚不存在),您应该绝对Online 也转换为 dict;那么你可以简单地update dict 并获取values。我的订单很重要,请确保使用collections.OrderedDict 或 Python 3.7。

>>> online_dict = {sub[0]: sub for sub in Online}
>>> online_dict.update(newsub_dict)
>>> list(online_dict.values())
[['Robot1', '30.9', 'Sending', '440'],
 ['Robot3', 'has no replacement'],
 ['Robot2', '50'],
 ['Robot4', 'new entry']]

【讨论】:

  • 谢谢。还有一件事,只有当机器人ID在在线列表上时,如何替换子列表?当机器人 id 不存在时,将子列表添加到在线列表中。
  • @HugoAguiar 查看我的编辑。
猜你喜欢
  • 1970-01-01
  • 2013-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-07
  • 2018-06-06
  • 2021-12-18
相关资源
最近更新 更多