[英]how do i remove the Nth element from my list until there's only one element remains and print that remaining element in python
[英]how do you remove the nth item in a list until only one element is left in the list in python
所以在這個程序中,我有:
n = int(input())
p1 = 'One'
p2 = 'Two'
p3 = 'Three'
p4 = 'Four'
p5 = 'Five'
list = [p1, p2, p3, p4, p5]
while len(list) > 1:
if len(list) > n+1:
n = n-1
list.pop((n) % len(list))
print (list)
例如, n = 3
並且所需的 output 是P4
,所以我必須刪除 p3。 刪除 p3 后,我將再次刪除第 n 個項目,但計數將從最后一個刪除項目之后的項目開始。 因為我刪除了 p3,所以我必須在 p4 上開始計數。 我如何在 p4 中開始計數? 我所做的循環從列表的最開始計算,即 p1。
完成初始代碼后,建議如下:
...
而 len(list) > 1:
if len(list) < n + 1:
n = n - 1
list.pop(n)
打印(列表)
我編輯了我的建議..希望我能更好地理解你在尋找什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.