[英]How to print a random string from a list, when given an input? (Python)
[英]How to fetch and print the list sequentially in a list given from a input file
對於特定場景,我使用列表 append 的組合並擴展以獲得所需的 output,但它沒有給出預期的 output。下面的代碼給出了 output [['test1', 'test2'], 'test3', 'test4', 'test5', 'test6', ['test5', 'test6']]
正如我所期望[['test1', 'test2'], ['test3', 'test4', 'test5', 'test6'], ['test5', 'test6']]
。 如果我想更改密鑰(輪胎 1、輪胎 2、輪胎 3)順序,它應該以新順序打印 output。
任何提示/建議都會很有幫助。 謝謝
輸入.json
{
"tire1": {
"source": [ "{{ 'PEP' | YYYYYYY | join }}" ]
},
"tire2": {
"source": [ "{{ 'REP, DEP' | LLLLLL | join }}" ]
},
"tire3": {
"source": [ "{{ 'DEP' | LLLLLL | join }}" ]
}
}
數據.json
{
"PEP": {
"tire2": {
"tire3": {
"compname": "test1"
},
"tire4": {
"compname": "test2"
}
}
},
"REP": {
"tire2": {
"tire3": {
"compname": "test3"
},
"tire4": {
"compname": "test4"
}
}
},
"DEP": {
"tire2": {
"tire3": {
"compname": "test5"
},
"tire4": {
"compname": "test6"
}
}
}
}
測試.py
import json
import re
def findkeysvalues(inputDict, key):
if isinstance(inputDict, dict):
if key in inputDict:
yield inputDict[key]
for j in inputDict.values():
for x in findkeysvalues(j, key):
yield x
def process_JSON_value(jsonFileInput, parentInputKey, key):
with open(jsonFileInput) as jsonFile:
data = json.load(jsonFile)
Dict = { }
for i in data:
if i == parentInputKey:
Dict[i] = data[i]
return list(findkeysvalues(Dict, key))
def elements():
with open("input.json") as jsonFile:
data = json.load(jsonFile)
lst = []
rules_items_source = list(findkeysvalues(data, "source"))
for i in rules_items_source:
listtostring = ' '.join([str(el) for el in i])
y = listtostring.split("|")
x = re.findall("\w+", y[0])
if len(x) != 1:
for j in x:
source = process_JSON_value("data.json", j, "compname")
lst.extend(source)
else:
source = process_JSON_value("data.json", x[0], "compname")
lst.append(source)
print(lst)
elements()
將您的 if 塊更改為此代碼:
if len(x) != 1:
source = []
for j in x:
source.extend(process_JSON_value("data.json", j, "compname"))
lst.append(source)
Output 與您當前的 input.json
[['test1', 'test2'], ['test3', 'test4', 'test5', 'test6'], ['test5', 'test6']]
如果我像這樣向 input.json 添加額外的值:
"tire2": {
"source": [ "{{ 'PEP, REP, DEP' | LLLLLL | join }}" ]
}
然后是 output:
[['test1', 'test2'], ['test1', 'test2', 'test3', 'test4', 'test5', 'test6'], ['test5', 'test6']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.