[英]Every n-th element of a list
我想刪除 Python 列表的每個第 n 個元素。 當我到達列表的末尾時,我想 go 回到我離開的地方並繼續這個過程,直到只剩下一個元素。
我的代碼是:
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)
但是,它沒有正常工作。
補充說明:如果n=3,我想讓它在第一步中刪除3和6。 第二步,必須從7繼續計數(上一個刪除元素的下一個元素。最后一個刪除元素是6。所以,必須從7開始計數)。 當它從 7 開始計數到 3 個元素時,它必須刪除 1。依此類推......
這是我想出的對我有用的解決方案。
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
這是一個循環數組問題,您需要刪除每個第 n 個元素,直到到達最后一個元素。 下面是它的解決方案
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]
我認為這個邏輯是正確的。
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.