从列表的列表中复制浮点值

Copy float values from within lists of lists

如果我没有在正确的地方寻找,我深表歉意,但我终其一生都无法弄清楚如何从 say 中获取价值 list[[1,2,3][4,5,6.01]] , list[1][2] 作为列表以外的任何东西集成到代码中。

import random
fruits = [
['mango',7],
['apple',4],
['kiwi',6],
['grape',12],
['pear',3]
]
#Finding Probability
def setup():
    fsum = 0;
    prob = 0;
    i = 0
    #Finding the sum
    while i < len(fruits):
        fsum += fruits[i][1]
        i += 1
    i = 0
    #Calculating Probability
    while i < len(fruits):
        prob = [fruits[i][1] / fsum]
        fruits[i].append(prob)
        i += 1
    print(fsum)
    print(fruits)
setup()
def pick(x):
    rand = random.random()
    index = 0
    while rand > 0:
        #How do I get the value of the float in the list from the next line
        #(fruits[index][2])
        #to be stored in a variable that I can plug into this.
        #rand = rand - (var)
        index+=1

pick (fruits)

Any feedback would be greatly appreciated.

只需访问 list/array 的第一项,使用索引访问和索引 0:

 var = fruits[index][2][0]

你的问题是这一行:

prob = [fruits[i][1] / fsum]

您将 prob 定义为一个只有一个值的列表,只需删除不需要的列表即可,例如:

prob = fruits[i][1] / fsum

那么fruits[index][2]就是概率

您应该考虑将 while 循环替换为 for 循环,例如:

while i < len(fruits):
    fsum += fruits[i][1]
    i += 1
i = 0

相当于:

for fruit in fruits:
    fsum += fruit[1]

这可以用生成器表达式来完成:

fsum = sum(fruit[1] for fruit in fruits)

但是如果你想做的只是根据相对重量 (fruits[i][1]) 挑选水果,那么在 Py3.6 中有一种更简单的方法可以做到这一点,而不需要 setup(),例如:

def pick(fruits):
    items, weights = zip(*fruits)
    return random.choices(items, weights)[0]

在 Py3.6 之前你可以这样做:

def pick(fruits):
    return random.choice([f for fruit in fruits for f in [fruit[0]]*fruit[1]])