[英]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.