【问题标题】:How can I remove two or more objects of a list from a single input in Python?如何从 Python 中的单个输入中删除列表的两个或多个对象?
【发布时间】:2021-02-27 05:24:07
【问题描述】:

这是我的示例数据库:

现在在我的脚本中,我使用以下代码向列表中添加元素:

import pandas
data = pandas.read_excel("Sample database copy.xlsx")
name = dict(zip(data["Abbreviation"],data["Name"]))
list1 = []
incoming_msg = input('Please type what you want to add: ')
incoming_msg = incoming_msg.split() # split the string by space
if len(incoming_msg) == 2: # if there are two elements in the list (number and name)
    list1 += [name[incoming_msg[1]]] * int(incoming_msg[0])
else:
    list1.append(name[incoming_msg[0]])

所以现在如果输入“2 JO”,我的列表将包含两个新元素“John”和“John”。

现在我想做完全相同的事情,但要消除列表中的对象。我试图将当前的运算符 "+=" 替换为 "-=" 但令人惊讶的是它不起作用。关于如何解决这个问题的任何想法?

PS。我需要从同一个输入中完成所有操作。我不能单独要求钥匙和数量。我想复制上述代码,但要删除对象。

【问题讨论】:

    标签: python python-3.x pandas list


    【解决方案1】:

    你可以使用list.<b>remove()</b>:

    从列表中删除值等于 x 的第一项。它 如果没有这样的项目,则会引发 ValueError。

    import pandas as pd
    
    data = pd.read_excel("Sample database copy.xlsx")
    name = dict(zip(data["Abbreviation"], data["Name"]))
    list1 = []
    
    incoming_msg = input('Please type what you want to add: ')
    incoming_msg = incoming_msg.split()  # split the string by space
    if len(incoming_msg) == 2:  # if there are two elements in the list (number and name)
        list1 += [name[incoming_msg[1]]] * int(incoming_msg[0])
    else:
        list1.append(name[incoming_msg[0]])
    
    print('\n'.join(list1))
    
    incoming_msg = input('Please type what you want to delete: ')
    incoming_msg = incoming_msg.split()  # split the string by space
    if len(incoming_msg) == 2:  # if there are two elements in the list (number and name)
        num_to_remove = int(incoming_msg[0])
        while name[incoming_msg[1]] in list1 and num_to_remove > 0:
            list1.remove(name[incoming_msg[1]])
            num_to_remove -= 1
    else:
        if name[incoming_msg[0]] in list1:
            list1.remove(name[incoming_msg[0]])
    
    print('\n'.join(list1))
    

    示例用法:

    Please type what you want to add: 4 JO
    John
    John
    John
    John
    Please type what you want to delete: 2 JO
    John
    John
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-07
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多