簡體   English   中英

從列表列表中復制浮點值

[英]Copy float values from within lists of lists

如果找不到合適的地方,我確實表示歉意,但是我一生都無法找出如何從list[[1,2,3][4,5,6.01]]list[1][2]獲取值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.

您的問題是這一行:

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

您將prob定義為具有一個值的列表,只需消除不必要的列表,例如:

prob = fruits[i][1] / fsum

然后, fruits[index][2]將是概率。

您應該考慮將for循環替換為while循環,例如:

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]])

只需使用索引訪問和索引0訪問列表/數組的第一項即可:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM