auto_now_add=True
如何从linux脚本中的列表中随机选择多个项?
例如: -
A栏B栏
enter code here
输入: - 要选择的项目数
例如: - 要选择的项目数= 6
Itemcode Quantity
COM#004 2
COM#005 3
COME001 10
COMT000 3
COMT001 3
COMH000 1
COMH000 1
COM#006 2
CT100H000 1
选择一组项目后,必须减少数量。应该能够为下一个选择选择项目,直到其数量为零。
它有效,但我希望维持库存。在输出1: - 选择COME001,股票显示为9,但在输出2,它没有被选中,它可以随机选择,但股票应保持为9而不是10
输出1: - $ python test.py 挑选:['COM#004','COM#005','COMH000','COM#004','CT100H000','COME001']
股票离开了 COMH000 1 COMT000 3 COMT001 3 CT100H000 0 COM#005 2 COM#004 0 COM#006 2 COME001 9
输出2: - $ python test.py 挑选:['COMH000','COMT000','COM#004','COM#006','COM#005','COMH000']
股票离开了 COMH000 0 COMT000 2 COMT001 3 CT100H000 1 COM#005 2 COM#004 1 COM#006 1 COME001 10
答案 0 :(得分:0)
如果速度不重要,可以在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
print "Picked:", lpicked
给出以下可能的输出:
Stock left
COMH000 0
COMT000 2
COMT001 3
CT100H000 0
COM#005 3
COM#004 2
COM#006 2
COME001 8
Picked: ['CT100H000', 'COMH000', 'COME001', 'COME001', 'COMH000', 'COMT000']
已更新以使用CSV文件。使用Python 2.7进行测试。
答案 1 :(得分:0)
您可以使用random.sample()
,
import random
# Reading in all the lines
with open('input') as f:
lines = f.readlines()
# Deleting first line
del lines[:1]
# Picking 6 unique list items randomly
print("\n".join(random.sample(lines, 6)))
请参阅https://docs.python.org/2/library/random.html?highlight=random%20sample#random.sample。