从Python中的嵌套列表中获取值

2024-03-29 11:28:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我要求一个值,它是产品的id。 我想要的是有这个id的产品的价格,最后一个号码。你知道吗

产品代码:

producto=[[0, "Patata", "PatataSL", 7], [1, "Jamon", "JamonSL", 21], [2, "Queso", "Quesito Riquito", 5], [3, "Leche", "Muu", 4], [4, "Oro", "Caro", 900], [5, "Zapatos", "Zapatito", 56], [6, "Falda", "Mucha ropa", 34]]
def productos():
    respuesta=True
    while respuesta:
        print ("""
        1.Mostrar Productos
        2.Salir al menu
        """)
        respuesta=input("Introduzca la opcion ") 
        if respuesta=="1":
            for r in producto:
                for c in r:
                    print(c, end = " ")
                print()
        elif respuesta=="2":
            import menu
        elif respuesta !="":
          print("\n No ha introducido un numero del menu") 

购物代码:

import clientes
import productos
def compras():
    respuesta=True
    while respuesta:
        print ("""
        1.Comprar
        2.Salir al menu
        """)
        respuesta=input("Introduzca la opcion ") 
        if respuesta=="1":
            i = int(input("Introduzca el id del cliente: "))
            if i in (i[0] for i in clientes.cliente):
                print("El cliente está en la lista")
            else:
                print("El cliente no está en la lista")
                compras()
            p = int(input("Introduzca el id del producto: "))
            if p in (p[0] for p in productos.producto):
                print("El producto esta en stock")

这些是我一直在尝试的事情,但是我得到了一个错误代码:TypeError:'int'对象是不可订阅的。你知道吗

for j in productos.producto:
                    for p in j:
                        print (str(p[3]))
                #print("El producto cuesta: " + str(p[p][3]))

最后一部分还可以。你知道吗

else:
                print("El producto no esta en stock")
                compras()           
        elif respuesta=="2":
          import menu
        elif respuesta !="":
          print("\n No ha introducido un numero del menu") 

Tags: inimportidforinputifella
3条回答

我假设您需要根据id打印产品的价格

producto=[[0, "Patata", "PatataSL", 7], [1, "Jamon", "JamonSL", 21], [2, "Queso", "Quesito Riquito", 5], [3, "Leche", "Muu", 4], [4, "Oro", "Caro", 900], [5, "Zapatos", "Zapatito", 56], [6, "Falda", "Mucha ropa", 34]]

我假设,索引0是id,索引3是Price。你知道吗

product_id = 0 //user input
for v in producto:
   if v[0] == product_id:
       print(v[0][3])

你需要给出价格指数

您只需添加一组额外的方括号就可以得到嵌套项,因此对于第一个嵌套列表中的7来说是producto[0][3]

您可以通过将列表中的最后一个元素称为-1元素来获取它。你知道吗

for productList in producto:
    if respuesta == productList[0]:
        print('Price:', productList[-1])

相关问题 更多 >