英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论