Python程序要删除并从列表中打印三分之一,直到它变空?
首先,我们创建一个列表,起始地址的索引为0,第一个第三个元素的位置为2,需要遍历直到列表为空,这是每次我们必须查找下一个索引时要做的另一项重要工作第三个元素并打印该值,然后减少列表的长度。
示例
A:[10,20,30,40] OUTPUT:30 20 40 10
说明
第一个第三元素是30,然后我们从40开始计算下一个第三元素20,然后从40开始计算下一个第三元素是40本身,最后打印10。
算法
步骤1:列表的索引从0开始,第一个第三个元素将在位置2。
variable p=2,starting index id=0.
步骤2:找到列表的长度。
listlen=len (LST) // length of the list(LST)
步骤3:遍历直到列表变空,每次都找到下一个第三个元素的索引。
While(listlen>0)
Id=(p+id)%listlen
A=LST.pop(id)// removes and prints the required element
Listlen-=1
End while范例程式码
# To remove to every third element until list becomes empty
def removenumber(no):
# list starts with
# 0 index
p = 3 - 1
id = 0
lenoflist = (len(no))
# breaks out once the
# list becomes empty
while lenoflist > 0:
id = (p + id) % lenoflist
# removes and prints the required
# element
print(no.pop(id))
lenoflist -= 1
# Driver code
A=list()
n=int(input("Enter the size of the array ::"))
print("Enter the INTEGER number")
for i in range(int(n)):
p=int(input("n="))
A.append(int(p))
print("After remove third element, The List is")
removenumber(A) # call function输出结果
Enter the size of the array ::9 Enter the number n=10 n=20 n=30 n=40 n=50 n=60 n=70 n=80 n=90 After remove third element, The List is 30 60 90 40 80 50 20 70 10
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短