gpt4 book ai didi

Python将数组打印成两个结果

转载 作者:行者123 更新时间:2023-11-30 21:56:08 24 4
gpt4 key购买 nike

我无法打印出第二行

我尝试使用除以2并使用两个for循环来打印它,

A=[1,2,3,4,5,6,7,8]
w=len(A)
T=w/2
for i in range(T):
for ii in range(T):
print A[ii]


A=[1,2,3,4,5,6,7,8]

我想打印 [1,2,3,4][5,6,7,8]

最佳答案

使用slicing :

A=[1,2,3,4,5,6,7,8]

print(A[:len(A)//2]) # print(A[:4])
print(A[len(A)//2:]) # print(A[4:])

输出:

[1, 2, 3, 4]
[5, 6, 7, 8]

编辑:

为了理解;

A=[1,2,3,4,5,6,7,8]
w = len(A)

first_part = []
sec_part = []
count = 0 # counter var to check for the first/sec half of list
for i in range((w)):
if count < w//2:
count += 1
first_part.append(A[i])
else:
sec_part.append(A[i])

print(first_part)
print(sec_part)

输出:

[1, 2, 3, 4]
[5, 6, 7, 8]

关于Python将数组打印成两个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55573502/

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