如何在Python中每次获取不同的行数以及每次执行时的值?

时间:2019-04-05 08:16:02

标签: python-3.x

我正在尝试执行以下代码,但无法正常工作。我也希望将不同的行作为输出和值。

name_list = ['red', 'blue', 'orange', 'black']

rr = [random.randint(1,100) for i in list1]
hh = zip(random.choice(list1), rr)
for i in range(random.randint(1,15)):
    for x,v in hh:
            print('"Book Color":',x,',', '"Price: "',v)

每次运行代码时,我都希望它会更改输出中的行数,并且还会更改每一行的价格。

第一次运行:

"Book color" : blue, "Price":45
"Book color" : red, "Price":65

第二次运行:

"Book color" : black, "Price":5
"Book color" : red, "Price":50
"Book color" : orange, "Price":75
"Book color" : blue, "Price":12

第3次运行:

"Book color" : orange, "Price":2

1 个答案:

答案 0 :(得分:0)

import random name_list = ['red', 'blue', 'orange', 'black'] list1 = [1,2,3,4,5,6] # change these values to actual prices for i in range(random.randint(1,15)): randomprice = random.choice(list1) randomcolor = random.choice(name_list) print('"Book Color":',randomcolor,',', '"Price: "',randomprice) 循环的每次迭代中只需选择随机的颜色和价格:

"Book Color": black , "Price: " 3
"Book Color": black , "Price: " 3
"Book Color": blue , "Price: " 1
"Book Color": orange , "Price: " 6
"Book Color": black , "Price: " 3
"Book Color": red , "Price: " 6

首次运行:

"Book Color": blue , "Price: " 6
"Book Color": orange , "Price: " 1
"Book Color": blue , "Price: " 5

第二次运行:

{{1}}