【问题标题】:Merge sublist with each item of list将子列表与列表的每个项目合并
【发布时间】:2023-01-08 04:14:39
【问题描述】:

我有一个列表列表,我需要将它们与列表的每个项目一起加入。请参见下面的示例:

my_list = [1, [2, 3], [4, 5]]

预期结果:

['1', '1.2', '1.3', '1.2.4', '1.2.5', '1.3.4', '1.3.5']

我尝试编写逻辑,但总是缺少一项或多项。

【问题讨论】:

  • 在问题中将您的代码显示为格式正确的文本。
  • 您是否正在尝试创建一个列表字符串结果?因为您所显示的预期结果不是有效的 Python 语法。
  • 是的,输出应该是每个项目的字符串

标签: python algorithm


【解决方案1】:
def join_lists(result, prefix, items):
    if not items:
        result.append('.'.join(map(str, prefix)))
    else:
        for i, item in enumerate(items[0]):
            join_lists(result, prefix + [item], items[1:])
        join_lists(result, prefix, items[1:])

my_list = [1, [2, 3], [4, 5]]
result = []
join_lists(result, [1], my_list)
print(result)

将产生:

Output: ['1', '1.2', '1.3', '1.2.4', '1.2.5', '1.3.4', '1.3.5']

【讨论】:

    【解决方案2】:

    结果 = []

    def join_lists(前缀,项目): 对于项目中的项目: 如果是实例(项目,列表): join_lists(prefix + "." + str(item[0]), item[1:]) 别的: 结果.附加(前缀+“。”+ str(项目))

    join_lists("1", my_list[1:])

    打印(结果)

    【讨论】:

      猜你喜欢
      • 2019-01-16
      • 2017-08-19
      • 1970-01-01
      • 1970-01-01
      • 2017-12-26
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 2017-09-28
      相关资源
      最近更新 更多