簡體   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