簡體   English   中英

試圖從python中的列表中刪除特定索引

[英]Trying to remove specific index from a list in python

我正在嘗試刪除特定的索引列表項並且無法弄清楚,或者任何使列表不那么復雜的方法。

a=True

list=[]

costs=[]

while a == True:

list.append()可能是個問題嗎?

    print('Select from the following list:\n1. Add Item\n2. View Cart\n3. Remove Item\n4. Compute Total\n5. Quit')

    choice= int(input('Please enter a number: '))
    print()

    if choice == 1:
        item= input('What item would you like to add? ').capitalize()
        cost= float(input(f'What is the cost of the {item}? '))

        print(f'{item} has been added to cart.\n')

        list.append(f'{item} '+ f'${cost:.2f}')
        costs.append(cost)

將列表項逐行顯示為: 1. 床 120 美元。

不是復雜性的最大粉絲,但它確實有效。

    elif choice == 2:

        line= "{{: >{}}}. {{}}\n".format(len(str(len(list))))

        for i, item in enumerate(list, start=1):

            if len(list) != 0:

                print(line.format(i, item))

            else:
                print('The Cart is Empty\n')

這應該刪除特定的索引項。 這是我遇到最多問題的地方。 我根本無法讓它工作:

    elif choice == 3:
        print('Which item would you like to remove?')
        num=int(input())

        if i in list:

            list=list.pop(i)  

            print(f'Item Removed')
        
        else:
            print('Invalid Input')

這將打印總成本:

    elif choice == 4:
        total=sum(costs)

        print(f'Your total is ${total:.2f}\n')


    elif choice == 5:
        print('Thank you for playing.')
        a=False
  • i in list測試i是否是列表中的值之一,但i是索引。 if i < len(list):
  • list.pop()返回被刪除的元素,而不是修改后的列表。 因此,當您執行list = list.pop(i)時,您將使用已刪除的元素替換列表。 您應該只調用list.pop(i)而不分配回變量,它會修改列表。
    elif choice == 3:
        print('Which item would you like to remove?')
        num=int(input())

        if i < len(list):
            list.pop(i)  
            print(f'Item Removed')
        else:
            print('Invalid Input')

此外,您不應該使用list作為變量名,因為它是內置類的名稱。

在 python 列表中,一些方法返回一個新列表,但其他方法更改現有列表並且不返回任何內容。

list.pop正在刪除正確的元素並將其返回:如果將其分配給列表,則變量將成為元素,而不是列表。

所以你應該調用該方法,並忽略它的返回:

lst = ["a", "b", "c"]

print(lst)
lst.pop(0)
print(lst)
python main.py 
['a', 'b', 'c']
['b', 'c']

如果您不需要該元素,也可以使用del

lst = ["a", "b", "c"]

print(lst)
del lst[0]
print(lst)

你有一些選擇 首先,確保不要使用list作為變量名 - list是一個內置類,“隱藏”該名稱會導致意外行為。

要從列表中刪除項目,您可以執行以下操作(在 REPL 中):

>>> ls = [1,2,3]
>>> ls.remove(2)
>>> ls
[1, 3]

按值刪除。 也就是說,它查找第一個匹配值並將其刪除。 不返回此值,並就地修改列表。

如果要按索引刪除,可以使用pop()

>>> ls = [1,2,3]
>>> x = ls.pop(0)
>>> x
1
>>> ls
[2, 3]

這將刪除提供的索引處的元素(在本例中為索引0 ),並返回該元素。 此列表已就地修改。

您可以使用[del][2]關鍵字:

>>> ls = [1,2,3]
>>> del ls[1]
>>> ls
[1, 3]

這將刪除引用的對象並將其從列表中刪除。

做你正在尋找的一個慣用的方式是這樣的:

ls = ... # Define your list
print('Which item would you like to remove?')
item_idx = int(input())

item = ls.pop(item_idx) if item_idx < len(ls) else None  # First do the task
if item is None:  # Then report what the result is
    print("Invalid item.")
else:
    print(f"Item removed: {}")

注意item_idx與列表長度進行比較,而不是它是否在列表中(即item_idx in ls )。 我在這里強調變量的命名,因為它有助於清楚地思考引擎蓋下實際發生的事情。

最后,關於字符串格式的“復雜性”的注釋。 您可能可以達到與line= "{{: >{}}}. {{}}\n".format(len(str(len(list))))類似的效果:

 for idx, item in enumerate(ls):
     print(f"{idx:>4} item")

這左對齊,並假設您有少於一萬個項目,但這可能會使代碼讀者更清楚正在發生的事情,而不會對輸出產生不良影響。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM