python-3.x 如何使用if-else语句的列表解析来打印操作是否已经完成?

p3rjfoxz  于 2023-01-10  发布在  Python
关注(0)|答案(2)|浏览(115)

所以我有一个代码,要求找到司机的名字,如果它存在,从主要的司机详细信息列表中删除该列表。我使用了一个嵌套列表来实现这一点。删除列表后,我希望显示一条消息,说“记录已删除”或“记录未找到”。

driver_details=[["Ken Block","55","Hoonigan","Mustang"], ["Ken Miles","48","Ford","Ford GT"]]

def delete_driver():
    """This function is used to delete driver details
    by entering the driver name"""
    global driver_details
    driver_name=input("Enter driver name: ")
    if driver_name in driver_details:
        driver_details=[x for x in driver_details if x[0] not in driver_name]
        print("Driver details deleted")
    else:
        print("Record Not Found")
    print(driver_details)
    options()

这似乎对我不起作用。
然而,当我尝试这个:

"""This function is used to delete driver details
    by entering the driver name"""
    global driver_details
    driver_name=input("Enter driver name: ")
    driver_details=[x for x in driver_details if x[0] not in driver_name ]
    print("Driver details deleted")
    print(driver_details)
    options()

它会删除记录。
我希望答案打印为记录已删除,但我一直得到记录未找到,即使驱动程序的名称确实存在。我怎么能添加一个如果语句到这一点?

0ve6wy6x

0ve6wy6x1#

您的代码对我来说非常好用。但是,有两处更正:
1.必须将嵌套字典driver_details展开才能检查in属性
1.存在排印错误,driver_name in drivers_details应为driver_name in driver_details
driver_details=[["Ken Block","55","Hoonigan","Mustang"], ["Ken Miles","48","Ford","Ford GT"]]

def delete_driver():
    """This function is used to delete driver details
    by entering the driver name"""
    global driver_details
    driver_name=input("Enter driver name: ")
    if driver_name in [item for sublist in driver_details for item in sublist]:  #flattened nested list
        driver_details=[x for x in driver_details if x[0] not in driver_name]
        print("Driver details deleted")
    else:
        print("Record Not Found")
    print(driver_details)
gcuhipw9

gcuhipw92#

下面是如何从driver_details中删除:

driver_details2 = [dd for dd in driver_details if dd[0] != driver_name]
driver_details[:] = driver_details2  # Overwrite original list.

你的代码还有一些其他的问题(因为它是发布的),例如drivers_list变量没有定义。你可以这样定义它:

drivers_list = [dd[0] for dd in driver_details]

相关问题