Python|从列表中删除并打印每三分之一,直到它变空
给定一个数字列表,您的任务是从数字列表中删除并打印每三个数字,直到列表为空。
例子:
Input : [10, 20, 30, 40, 50, 60, 70, 80, 90]
Output : 30 60 90 40 80 50 20 70 10
Explanation:
The first third element encountered is 30, after 30 we start the count from 40 for the next third element which is 60, after that 90 is encountered. Then again the count starts from 10 for the next third element which is 40. Proceeding in the same manner as we did before we get next third element after 40 is 80. This process is repeated until the list becomes empty.
Input : [1, 2, 3, 4]
Output : 3 2 4 1
Explanation:
The first third element encountered is 3, after 3 we start the count from 4 for the next third element which is 2. Then again the count starts from 4 for the next third element which is 4 itself and finally the last element 1 is printed.
方法列表的索引从0开始,第一个第三个元素将在位置2。遍历直到列表变为空,每次找到下一个第三个元素的索引并打印其对应的值。打印后减少列表的长度。
# Python program to remove to every third
# element until list becomes empty
def removeThirdNumber(int_list):
# list starts with
# 0 index
pos = 3 - 1
index = 0
len_list = (len(int_list))
# breaks out once the
# list becomes empty
while len_list > 0:
index = (pos + index) % len_list
# removes and prints the required
# element
print(int_list.pop(index))
len_list -= 1
# Driver code
nums = [1, 2, 3, 4]
removeThirdNumber(nums)
输出:
3
2
4
1