繁体   English   中英

我如何从我的列表中删除第 N 个元素,直到只剩下一个元素并在 python 中打印剩余的元素

[英]how do i remove the Nth element from my list until there's only one element remains and print that remaining element in python

name1 = input("name2: ")
name2 = input("name1: ")

def popcommonchar(name1, name2):
    str1 = ''
    for s in (name1):
        if s not in name2:
            str1 += s 

    str2 = ''
    for s in (name2):
        if s not in n1:
            str2 += s

    list = ["A", "B", "C", "D", "E", "F"]
    while True:
        if len(list) == 1:
            break

        e = (len(str1)) + (len(str2))
        sum =+ e
        list.pop(e)
        print(list)

popcommonchar(name1, name2)

删除列表中的第 5 个项目后,我希望程序继续计数并弹出/删除第 5 个元素。 当 N 是strstr2长度的总和时,我想从列表["A", "B", "C", "D", "E", "F"] 中删除第 N 个项目。

删除F后,提示错误,如何解决?

您需要维护删除播放器的索引和您的 k 到它(在这种情况下为 5),当列表的长度变得小于数字时,使用列表长度对数字取模,以便它为您提供需要删除的下一个索引。

l1 = ["A1", "B2", "C3", "D4", "E5", "F6"]
k = 5
currentIndex = 0
while len(l1) != 1:
    currentIndex = (currentIndex + k - 1) % len(l1)
    l1.pop(currentIndex) 
    print(l1)

Output:
['A1', 'B2', 'C3', 'D4', 'F6']
['A1', 'B2', 'C3', 'F6']
['A1', 'B2', 'C3']
['A1', 'C3']
['A1']

天真的解决方法是在当前长度内保持旋转索引。 代替

sum =+ e

sum = (sum + e) % len(l1)

然而,最简单也可能是最deque.rotate方法是使用deque.rotate

from collections import deque

q = deque(["A1", "B2", "C3", "D4", "E5", "F6"])
e = 5

while len(q) > 1:
    q.rotate(1-e)
    print(q.popleft())
print(q)

E5
D4
F6
B2
C3
deque(['A1'])

请记住,pop() 删除项目,并且列表在弹出后更改长度。 因此,您可以只使用 pop() 而不带结束项的参数。 我的意思是你必须在你的代码l1.pop(e)更改为l1.pop()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM