我的 .json 檔案包含:
"message": [
{
"first": [
"hi",
"hii"
],
"second": [
"bye",
"byee"
]
}
]
我希望 Python 隨機列印hi or hii并且bye or byee,choice適合這里。
但要使用它,我首先需要列印 和 的first值second。
我的代碼只列印
first
second
這里是:
def read_settings(file):
with open(file, encoding = 'utf-8') as f:
return load(f)
# Read json file
file = read_settings('settings.json')
for i in file['message'][0]:
print(i)
我要列印
hi # or hii
bye # or byee
uj5u.com熱心網友回復:
嘗試使用random帶有串列理解的模塊:
random.choice([x for y in myFile["message"][0] for x in myFile["message"][0][y]])
請注意,我已經更改了您命名的變數,file因為myFile它file是在 python 中預定義的。
此函式回傳串列的隨機元素["hi", "hii", "bye", "bye"]。但是如果你想回傳firstkey 或secondkey 的值,你可以嘗試:
random.choice([myFile["message"][0][x] for x in myFile["message"][0]])
這一個,實際上回傳一個串列。它回傳['hi', 'hii']或['bye', 'byee']
uj5u.com熱心網友回復:
當您像 () 一樣遍歷字典時for i in file['message'][0]:,它只會獲取該字典的鍵。要使用密鑰列印隨機值,請嘗試使用:
import random
for key, values in file['message'][0].items():
print(random.choice(values))
uj5u.com熱心網友回復:
你的代碼片段
for i in file['message'][0]:
print(i)
只需列印 python 的密鑰dictionary:
{'first': ['hi', 'hii'], 'second': ['bye', 'byee']}
為了獲得values所需的輸出,只需修改您的代碼以匯入隨機庫
import random
...
...
...
for i in file['message'][0]:
values = file['message'][0][i]
random.choices(values)
uj5u.com熱心網友回復:
import random
for option in file['message']:
for value in option.keys():
print(option[value][random.randrange(0,2)])
for option in file['message']-> 回傳 'first' 和 'seccond' 及其值(“hi”、“hii”和“bye”、“byee”)
for value in option.keys():-> 只選擇“第一”和“第二”值
print(option[value][random.randrange(0,2)])-> 選擇“hi”或“hii”,(option[0][0] 將是“hi”),所以選擇 option[0][0 到 1 之間的隨機值]。
這樣,您的值就會隨機生成。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/442688.html
上一篇:如何根據字串鍵檢索json值
