如果速度不重要,可以在Python中使用以下方法。数据必须存储在CSV文件中,并每次更新。我假设一个简单的制表符分隔的文件,如问题所示:import random, collections, csv
def pick_non_zero(count):
ditems = collections.defaultdict(int)
# Read the current stock file in
with open("stock.csv", "r") as f_input:
csv_input = csv.reader(f_input, delimiter="\t")
headers = csv_input.next()
for item, quantity in csv_input:
ditems[item] += int(quantity)
lchoices = []
for n in range(count):
# Create a list of items with quantity remaining
lnon_zero = [item for item, quantity in ditems.items() if quantity > 0]
if len(lnon_zero) == 0:
lchoices.append("No more stock")
break
# Pick one
choice = random.choice(lnon_zero)
# Reduce quantity by 1
ditems[choice] -= 1
lchoices.append(choice)
# Write the updated stock back to the file
with open("stock.csv", "wb") as f_output:
csv_output = csv.writer(f_output, delimiter="\t")
csv_output.writerow(headers)
for item, quantity in ditems.items():
csv_output.writerow([item, quantity])
print "Stock left"
for item, quantity in ditems.items():
print "%-10s %d" % (item, quantity)
return lchoices
lpicked = pick_non_zero(6)
print "Picked:", lpicked
给出以下可能的输出:
^{pr2}$
更新为使用CSV文件。使用Python2.7进行了测试。在