[英]Python append more than one element
I have a list(T) of 6500 images(arrays) that I am using for image classification, and I would like to see how increasing the data affects the accuracy.我有一个包含 6500 个图像(数组)的列表(T),用于图像分类,我想看看增加数据如何影响准确性。
So, starting from n=2000 images, I am thinking of having a loop that will add 500(n+=500) images at each iteration till it reaches 6500 and therefore compare the accuracy between 2000, 2500, 3000, ... 6500. I have simplified the problem below by having a list of 20 elements.因此,从 n=2000 图像开始,我正在考虑有一个循环,在每次迭代中添加 500(n+=500)张图像,直到达到 6500,因此比较 2000、2500、3000、... 6500 之间的精度。我通过列出 20 个元素简化了下面的问题。
lst = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0]
My second list ( slist
) contains the first 9 elements of the first list ( lst
).我的第二个列表( slist
)包含第一个列表( lst
)的前 9 个元素。
I am trying to add 2 values to slist
at each iteration, starting from lst[9:]
.从lst[9:]
开始,我试图在每次迭代中向slist
添加 2 个值。 I know rather than using append
, extend
should be used to add multiple values at once.我知道而不是使用append
,应该使用extend
一次添加多个值。 However, I couldn't find a way to do it.但是,我找不到办法做到这一点。
In the following code, one element is added to slist
(from lst
) at each loop.在以下代码中,在每个循环中将一个元素添加到slist
(来自lst
)。
lst = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0]
slist = lst[:9]
for i in lst[9:]:
slist.append(i)
How can I add 2 or 3 elements simultaneously at each loop?如何在每个循环中同时添加 2 或 3 个元素? An example output would be:例如 output 将是:
[1,2,3,4,5,6,7,8,9,0,1]
[1,2,3,4,5,6,7,8,9,0,1,2,3]
[1,2,3,4,5,6,7,8,9,0,1,2,3,4,5]
You could try using extend
:您可以尝试使用extend
:
l = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0]
slist = l[:9]
for i in l[9:][::2]:
if i == l[9]:
slist.extend(l[9+i: 9+i+1])
else:
slist.extend(l[9+i-1: 9+i+1])
print(slist)
Output: Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0]
lst=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,20]
iter = 9
while True:
print(lst[:iter])
iter+=2
if len(lst) <= iter:
print(lst[:iter])
break
This code does the job这段代码完成了工作
lst=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,21]
slist= lst[:9]
s,f=0,2
while True:
slist.extend(lst[9:][s:f])
print(slist)
s+=2
f+=2
if len(slist) >= len(lst):
break
It prints out:它打印出来:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.