【问题标题】:Conditional merging of sublists in a list列表中子列表的条件合并
【发布时间】:2019-04-12 09:16:16
【问题描述】:

我有以下列表。

If last sublist has len>1:

x = [[0], [1, 2, 3], [4, 5], [6], [7, 8, 9], [10, 11, 12, 13], [15], [16, 17, 18]]

expected_output = [[0, 1, 2, 3], [4, 5], [6, 7, 8, 9], [10, 11, 12, 13], [15, 16, 17, 18]]

If last sublist has len==1:

x = [[0], [1, 2, 3], [4, 5], [6], [7, 8, 9], [10, 11, 12, 13], [15], [16, 17, 18], [19]]

expected_output = [[0, 1, 2, 3], [4, 5], [6, 7, 8, 9], [10, 11, 12, 13], [15, 16, 17, 18], [19]]

我正在尝试将长度为 1 的子列表与下一个子列表合并。

如果最后一个子列表长度为 1,我想保持原样。

我尝试编写以下代码。

xt = []
for i in range(len(x)-1):
    if len(x[i]) == 1:
        xt.append(x[i]+x[i+1])
#         del x[i+1]
    if len(x[i])>1:
        xt.append(x[i])
print(xt)

【问题讨论】:

  • 但在这两种情况下,长度为 1 的子列表都会与下一个子列表合并。这个假设正确吗?
  • 是的。仅当最后一个子列表的长度为 1 时,我才想保持原样。

标签: python arrays python-3.x list


【解决方案1】:

试试这个:

def ref1(l):
    con = 0
    l2 = []
    while con<len(l)-1:
        if len(l[con])==1:
            l2.append(l[con]+l[con+1])
            con +=2
        else:
            l2.append(l[con])
            con+=1
    if len(l[-1])==1:
        l2.append(l[-1])
    print(l2)

ref1([[0], [1, 2, 3], [4, 5], [6], [7, 8, 9], [10, 11, 12, 13], [15], [16, 17, 18]])
# OUTPUT : [[0, 1, 2, 3], [4, 5], [6, 7, 8, 9], [10, 11, 12, 13], [15, 16, 17, 18]]

ref1([[0], [1, 2, 3], [4, 5], [6], [7, 8, 9], [10, 11, 12, 13], [15], [16, 17, 18], [19]])
# OUTPUT : [[0, 1, 2, 3], [4, 5], [6, 7, 8, 9], [10, 11, 12, 13], [15, 16, 17, 18], [19]]

【讨论】:

    【解决方案2】:

    代码分析

    xt = []
    for i in range(len(x)-1):
        if len(x[i]) == 1:
            xt.append(x[i]+x[i+1])
    

    这意味着您要在访问之前添加下一个子列表

    #         del x[i+1]
        if len(x[i])>1:
            xt.append(x[i])
    

    并且这没有关于子列表是否已合并的历史记录。

    print(xt)
    

    建议

    • 反过来访问列表,每次检查前一个列表的长度是否为 1。

    • 如果上一个操作是合并,请保留标签。

    TO OP

    如果您需要更多帮助,请大声喊叫

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-07
      • 2014-01-26
      • 2021-02-21
      • 2017-04-29
      • 2012-09-07
      • 2019-11-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多