[英]Every n-th element of a list
I want to delete every n-th element of a Python list.我想删除 Python 列表的每个第 n 个元素。 When I reach the end of the list, I want to go back to beginning from where I left off and to continue this process until only one element remains.当我到达列表的末尾时,我想 go 回到我离开的地方并继续这个过程,直到只剩下一个元素。
My Code is:我的代码是:
my_list=[1 2 3 4 5 6 7 8]
n=3
while len(my_list)>1:
del my_list[n-1::n]
print(my_list)
But, it didn't work corretly.但是,它没有正常工作。
Extra Explanation: If n=3, I want it to delete 3 and 6 in the first step.补充说明:如果n=3,我想让它在第一步中删除3和6。 For the second step, it must to continue to count from 7 (next element of the last deleted element. Last deleted element was 6. So, it must to start to count from 7).第二步,必须从7继续计数(上一个删除元素的下一个元素。最后一个删除元素是6。所以,必须从7开始计数)。 When it count to 3 element starting from 7, it must to delete 1. So on...当它从 7 开始计数到 3 个元素时,它必须删除 1。依此类推......
Here is the solution that i came up with that worked for me.这是我想出的对我有用的解决方案。
nums = [1,2,3,4,5,6,7,8]
pos=3-1 #since list starts from '0'
index = 0
len_list = (len(nums))
while len_list > 1:
index = (pos + index) % len_list
print(nums.pop(index)) # removes and prints the required element
len_list -= 1
print(nums[0]) #print the last remaining number in the list
Output:7 Output:7
This is a circular array problem where you need to delete every nth element till you reached the last element.这是一个循环数组问题,您需要删除每个第 n 个元素,直到到达最后一个元素。 Below is the solution for it下面是它的解决方案
my_list=[1, 2, 3, 4 ,5, 6, 7, 8]
def func(lis,n):
if n>len(lis):
return -1
while len(lis)!=1:
del lis[::n]
return lis
print(func(my_list, 3))
# output [8]
I think this logic is correct.我认为这个逻辑是正确的。
def f(a,n):
if len(a) == 1:
return a[0]
elif n - len(a) == 1:
return a[-1]
if len(a) < n:
a.extend(a[:n-len(a)])
q,r = divmod(len(a),n)
if r == 0:
first,second = a,[]
else:
first,second = a[:-r],a[-r:]
del first[n-1::n]
second.extend(first)
return f(second,n)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.