Python:添加条目?

2024-04-25 12:17:43 发布

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

我正在尝试编写一个程序,要求用户输入产品名称、价格和数量。从那里,所有的信息将被添加到一个表(字典?)此外,必须为创建的所有新项目分配一个ID号。我对身份证号码部分感到困惑。你知道吗

items = {}

product = str(input("Enter the name of a product: "))
price = int(input("Enter a price: "))
quantity = int(input("Enter a quantity: "))

#Assign unique ID number.

我试图以下面的结果为例:

ID#70271, shoes. 7 available, at $77.00

Tags: 项目用户程序信息idinput数量字典
3条回答

你需要能够检索信息吗?您可以考虑使用多个字典键,或者只想使用元组或列表。你知道吗

您几乎肯定需要导入一些东西来创建ID,特别是如果它是随机的。下面是一些代码,可以将这些信息添加到已经存在的填充或空列表中。你知道吗

def storesInfo(product,quantity,price,listInfo): #takes list as a variable
    import random
    ID = random.randrange(0,10000)
    listInfo.append([product,price,quantity,ID])
    return('ID%s, %s. %f available, at %f.'%(ID, product, quantity, price),listInfo)

def main():
    product = str(input("Enter the name of a product: "))
    price = int(input("Enter a price: "))
    quantity = int(input("Enter a quantity: "))
    listA = [[2983, 'socks',32,65.23],[9291,'gloves',98,29.00]]
    print(storesInfo(product,quantity,price,listA))

main()

您可以使用uuid4来创建唯一的id

>>> from uuid import uuid4
>>> uuid4().clock_seq
7972L
>>> uuid4().clock_seq
11807L
>>> uuid4().clock_seq
15487L
items = {}
import hashlib
product = "dinosaur"
price = 10.99
quantity = 20
uid = hashlib.md5(product).hexdigest() #is one way but you probably don't
# need a hash if you just want simple number id's: a much easier way is 
otheruid = len(items) # just have the next item be the UID
items[otheruid] = (product, price, quantity) 

相关问题 更多 >