繁体   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