gpt4 book ai didi

python - 有条件合并列表中的子列表

转载 作者:行者123 更新时间:2023-11-30 21:55:53 25 4
gpt4 key购买 nike

我有以下列表。

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)

最佳答案

试试这个:

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]]

关于python - 有条件合并列表中的子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55648306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com