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 新生祝福语简短8字
11 我想找祝福语大全简短
12 女朋友祝福语简短新年
13 启程出发路途祝福语简短
14 求简短的职场祝福语
15 祝妹妹毕业祝福语简短
16 小姨生日祝福语简短独特
17 直播生孩子祝福语简短
18 公司春节祝福语和简短