简体   繁体   English

试图从python中的列表中删除特定索引

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

I am trying to remove a specific indexed list item and haven't been able to figure it out, or any way to make the list less complicated.我正在尝试删除特定的索引列表项并且无法弄清楚,或者任何使列表不那么复杂的方法。

a=True

list=[]

costs=[]

while a == True:

Could the list.append() be an issue? 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)

Displays list items line by line as: 1. Bed $120.将列表项逐行显示为: 1. 床 120 美元。

Not the biggest fan of the complexity, but it worked.不是复杂性的最大粉丝,但它确实有效。

    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')

This is supposed to remove a specific index item.这应该删除特定的索引项。 This is where I am running into the most issue.这是我遇到最多问题的地方。 I haven't been able to get this to work at all:我根本无法让它工作:

    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')

This prints the total of costs:这将打印总成本:

    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 tests whether i is one of the values in the list, but i is an index. i in list测试i是否是列表中的值之一,但i是索引。 Use if i < len(list): if i < len(list):
  • list.pop() returns the element that was removed, not the modified list. list.pop()返回被删除的元素,而不是修改后的列表。 So when you do list = list.pop(i) , you're replacing the list with the removed element.因此,当您执行list = list.pop(i)时,您将使用已删除的元素替换列表。 You should just call list.pop(i) without assigning back to the variable, it modifies the list in place.您应该只调用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')

Also, you shouldn't use list as a variable name, since it's the name of a built-in class.此外,您不应该使用list作为变量名,因为它是内置类的名称。

In python lists, some methods return a new list, but others change the existing list and don't return anything.在 python 列表中,一些方法返回一个新列表,但其他方法更改现有列表并且不返回任何内容。

list.pop is removing the right element and returning it: if you assign it to your list, your variable becomes the element, not the list. list.pop正在删除正确的元素并将其返回:如果将其分配给列表,则变量将成为元素,而不是列表。

So you should invoke the method, and ignore its return:所以你应该调用该方法,并忽略它的返回:

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

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

If you don't need the element, you can also use del :如果您不需要该元素,也可以使用del

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

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

You have some options .你有一些选择 First, be sure not to use list as a variable name - list is a built-in class and 'shadowing' that name will cause unexpected behavior.首先,确保不要使用list作为变量名 - list是一个内置类,“隐藏”该名称会导致意外行为。

To remove an item from a list you can do the following (in the REPL):要从列表中删除项目,您可以执行以下操作(在 REPL 中):

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

This removes by value .按值删除。 That is, it looks for the first matching value and removes it.也就是说,它查找第一个匹配值并将其删除。 This value is not returned, and the list is modified in-place.不返回此值,并就地修改列表。

If you want to remove by index , you can use pop() :如果要按索引删除,可以使用pop()

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

This removes the element at the provided index (in this case index 0 ), and returns the element.这将删除提供的索引处的元素(在本例中为索引0 ),并返回该元素。 This list is modified in-place.此列表已就地修改。

You can use the [del][2] keyword:您可以使用[del][2]关键字:

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

This deletes the referenced object and removes it from the list in place.这将删除引用的对象并将其从列表中删除。

An idiomatic way of doing what you're looking for is this:做你正在寻找的一个惯用的方式是这样的:

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: {}")

Noting that the item_idx is being compared against the list length, not whether it is in the list (ie item_idx in ls ).注意item_idx与列表长度进行比较,而不是它是否在列表中(即item_idx in ls )。 I'm stressing the naming of the variables here, because it helps to think clearly about what is actually happening under the hood.我在这里强调变量的命名,因为它有助于清楚地思考引擎盖下实际发生的事情。

Finally, a note on the 'complexity' of string formatting.最后,关于字符串格式的“复杂性”的注释。 You can probably achieve a similar effect to line= "{{: >{}}}. {{}}\n".format(len(str(len(list)))) with:您可能可以达到与line= "{{: >{}}}. {{}}\n".format(len(str(len(list))))类似的效果:

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

This left-aligns, and assumes you have fewer than ten thousand items, but that should probably make it clearer to the reader of the code what is going on without impacting the output poorly.这左对齐,并假设您有少于一万个项目,但这可能会使代码读者更清楚正在发生的事情,而不会对输出产生不良影响。

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

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