簡體   English   中英

random.choices 和 if/else 語句

[英]random.choices and if/else statements

我正在嘗試列出一份清單,以便您了解姓名、他們的行為和行動。 我只是似乎沒有讓我的if/else語句起作用。 它只選擇我的else 從來沒有我的if即使那應該有更高的概率。 這是我的代碼:

import random

Names = ['john', 'james', 'dave', 'ryan']
behaviour = ['good', 'bad']
good = ['candy', 'presents', 'hug']
bad = ['get coal', ' have to stand in the corner']
for i in Names:
    n = random.choices(behaviour,weights=(3,1))
    k = random.choice(bad)
    if n=='good':
         print('{} was good this year therefor they get {}'.format(i,random.choice(good)))
    else:
         print('{} was bad this year therefor they {}'.format(i,random.choice(bad)))

今年我所有的東西都只是名字不好,所以他們得到了,然后是煤炭或角落......

那是因為random.choices返回一個list ,因此它永遠不會等於一個字符串(例如'good' )。

將其更改為:

n = random.choices(behaviour, weights=(3,1))[0]

文檔中

random.choices(population, weights=None, *, cum_weights=None, k=1)

返回 ak 大小的元素列表

它將返回一個list ,但是您將它與單個字符串'good'進行比較-它們永遠不會相同,並且它總是會選擇else塊。

例如,您可以:

    if n == ['good']:
         print('{} was good this year therefor they get {}'.format(i,random.choice(good)))
    else:
         print('{} was bad this year therefor they {}'.format(i,random.choice(bad)))

或者:

    if n[0] == 'good':

Random.choices 產生一個包含一個成員的列表。 要與字符串“good”進行比較,您需要使用 n[0] 對該項目進行索引

if n[0]=='good':
         print('{} was good this year therefor they get {}'.format(i,random.choice(good)))

我發現拋出一個打印語句來比較變量並驗證它們是我認為的那樣很有幫助。 這是測試問題的好方法。 像這樣的測試打印

print(n, 'good', n=='good', str(n)=='good')

在 if 語句給出這個 output 之前

['good'] good False False

這對於問題所在具有相當的指導意義。

暫無
暫無

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

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