问题:编写执行以下操作的python代码:
对于给定的正数数组,执行以下操作:
-
a) 创建一个新数组,并将第一个数组中的数字复制到第二个数组,而不复制重复的数字。(第二阵列元素应该是唯一的)
b) 在创建第二个数组时,为添加到数组中的每3个数字添加一个额外的-1整数。(从第一个数组复制
5, 6, 7
后,第二个数组内容应为5, 6, 7, -1
) -
创建第二个数组后,将其打印到控制台行将仅具有第二阵列的3个元素。
限制:
- 不允许使用
while
循环 - 除了在代码开头初始化第一个和第二个数组外,不允许在代码中使用
[
和]
字符
示例:
输入:
[5, 3, 20, 7, 32, 5, 2, 4, 19, 5, 45, 1, 7, 3, 2, 9, 5, 7, 6, 27, 74 ]
结果数组:
[5, 3, 20, -1, 7, 32, 2, -1, 4, 19, 45, -1, 1, 9, 6, -1, 27, 74]
输出:
5 3 20
7 32 2
4 19 45
1 9 6
27 74
我的作品:
A=[5,3,20,7,32,5,2,4,19,5,45,1,7,3,2,9,5,7,6,27,74]
B=[]
counter=0
n=1
for i in A:
if i not in B:
B.append(i)
counter+=1
if counter==3*n:
B.append(-1)
n+=1
print(B)
这就是我得到的输出:
[5, 3, 20, -1, 7, 32, 2, -1, 4, 19, 45, -1, 1, 9, 6, -1, 27, 74]
如果不使用括号[]
,我不知道如何将输出打印为他们想要的。我希望你能以某种方式帮助我。
你非常接近!您只需要添加另一个for
循环即可打印元素:
如果i == -1
,则打印新行以分隔这些内容,如果不是,则打印列表中由end=" "
(空格字符)分隔的内容B
:
for i in B:
if i == -1:
# prints a new line character
# print("n") if you need a blank line between entries
print()
else:
# end specifies how your elements will be seperated
print(i, end=" ")
使用您的输入,这将打印:
5 3 20
7 32 2
4 19 45
1 9 6
27 74
您可以在简单的for循环中按值对Python中的数组(以及任何其他可迭代的数组)进行迭代,从而实现
for element in B:
if element == -1:
print #this will just print new line marker
else:
print element, #notice the comma - it will not add new line marker
将在一行中打印B
容器的元素,并在-1
元素上添加新行。
此处使用的打印语义假定Python 2.X。如果您使用的是Python 3.X,则需要将它们更改为适当的语句,以打印新行print()
和不打印print(element, end=' ')
的语句