如何从一个数组创建所有子数组?SyntaxError: 无法在此处使用星号表达式

huangapple go评论68阅读模式
英文:

How to create all subarays form one array? SyntaxError: cannot use starred expression here

问题

To achieve your desired output, you can modify your code like this:

a = [1, 2, 3]
b = []
for i in range(len(a)):
    for j in range(len(a)):
        if j >= i:
            b = a[i:j + 1]
            print(b)

This code will produce the output you mentioned:

[1]
[2]
[3]
[1, 2]
[2, 3]
[1, 2, 3]

I removed the asterisk (*) before a[i:j+1] to fix the SyntaxError, and I added a print(b) statement inside the loop to print each subarray as desired.

英文:

My code

a =[1,2,3]
b = []
for i in range(len(a)):
    for j in range(len(a)):
        if j>=i:
            b=(*a[i:j+1])

print (b)

I got error

    b=(*a[i:j+1])
       ^^^^^^^^^
SyntaxError: cannot use starred expression here

This was my desired output

[1]		
[2]		
[3]		
[1,2]		
[2,3]		
[1,2,3]	

WHat should I change?

答案1

得分: 1

我认为你应该尝试这样做:

a = [1, 2, 3]
b = []

for i in range(len(a)):
    for j in range(len(a)):
        if j >= i:
           subarray = a[i:j+1]
           b.append(subarray)

print(b)
英文:

well i think u should try this

a = [1, 2, 3]
b = []

for i in range(len(a)):
    for j in range(len(a)):
        if j >= i:
           subarray = a[i:j+1]
           b.append(subarray)

 print(b)

huangapple
  • 本文由 发表于 2023年6月25日 17:59:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76549828.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定