gpt4 book ai didi

python - 将数组元素彼此分开

转载 作者:行者123 更新时间:2023-12-01 07:37:40 25 4
gpt4 key购买 nike

我试图将不同数组中连续数字的每个连续段分开。例如,

# Input
x=[1,2,3,4,5,8,11,12,13,18]
# Output:
x=[[1,2,3,4,5],[8],[11,12,13],[18]]

现有代码,

x=[1,2,3,4,5,8,11,12,13,18]
temp=[]

firstnumber=0
for i in range(1,len(x)-1,1):
current=x[i]
previous=x[i-1]
if ((current-previous)!=1):
mm=(x[firstnumber:i-1])
temp.append(mm)
firstnumber=x[i]
print(temp)


结果我只得到 [[1, 2, 3, 4], []],但我不明白为什么。

最佳答案

我试图回答这个问题,并尽可能少地更改您的代码。

x=[1,2,3,4,5,8,11,12,13,18]
temp=[]

firstnumber=0
first_index = 0
for i in range(1, len(x)):
current=x[i]
previous=x[i-1]
if ((current-previous)!=1):
mm = x[first_index:i]
temp.append(mm)
firstnumber = x[i]
first_index = i

temp.append(x[first_index:])

print(temp) # [[1, 2, 3, 4, 5], [8], [11, 12, 13], [18]]

我改变了什么:firstnumber 被用作索引,但实际上是列表的一个元素,因此我们需要使用 first_index = i,即该迭代的当前索引。

循环没有覆盖列表的所有元素,我们需要一直走到列表的末尾,因此我们迭代 range(1, len(x)

最后,即使循环完成,它也会丢失最后一个序列,除非我们在循环之后添加它,因此添加 temp.append(x[first_index:])

注意:此方法将适用于您拥有的输入,但它不适用于所有情况,也不是最有效的方法,但是,您的问题是为什么它不能按原样工作,所以希望这能回答.

关于python - 将数组元素彼此分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56907675/

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