我正在尝试编写一个程序,要求用户输入产品名称,价格和数量。从那里,所有信息将被添加到表(字典?)中。此外,必须为创建的所有新项目分配ID号。我对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
答案 0 :(得分:0)
您可以使用uuid4创建唯一ID
>>> from uuid import uuid4
>>> uuid4().clock_seq
7972L
>>> uuid4().clock_seq
11807L
>>> uuid4().clock_seq
15487L
答案 1 :(得分:0)
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)
答案 2 :(得分:0)
您是否需要能够检索信息?您可能会考虑使用多个字典键,或者只想使用元组或列表。
您几乎肯定需要导入一些东西来创建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()