我正在嘗試清理此代碼。
例如
data = [
{
"version": "11g",
"edition": "Enterprise",
"build_number": "11.2.0.4.0",
"path": "",
"devices": [
{
"host_name": "server1",
"manufacturer": "HP",
},
{
"host_name": "server2",
"manufacturer": "HP",
}
]
},
{
"version": "11g",
"edition": "Enterprise",
"build_number": "11.2.0.4.0",
"path": "",
}
]
for each in data:
version = each["version"]
if "devices" in each:
for server in each["devices"]:
hostname = server["host_name"]
print(version, hostname)
else:
hostname = None
print(version, hostname)
這會列印出我想要的以下內容。有沒有辦法在不使用兩個列印陳述句的情況下做到這一點?
11g服務器1
11g服務器2
12g 無
uj5u.com熱心網友回復:
空物件 (1 print)
如果您想在(version, None)沒有 的each情況下列印"devices",那么可以這樣做:
for each in data:
version = each["version"]
for server in each.get("devices", [{"host_name": None}]):
hostname = server["host_name"]
print(version, hostname)
說明:如果each沒有"devices",則get()回傳一個包含一個假設備 ( [{"host_name": None}]) 的串列,其中包含您要在沒有設備時列印的主機名。
為了便于閱讀,我會將那個假設備保存到一個命名常量中:
NONE_DEVICE = {"host_name": None}
for each in data:
version = each["version"]
for server in each.get("devices", [NONE_DEVICE]):
hostname = server["host_name"]
print(version, hostname)
這類似于“空物件”設計模式,在沒有物件時回傳一個特殊的“空”物件。
我的解決方案(2print秒)
然而,是否適合用一些特殊的物體來偽造丟失的設備,而不是僅僅承認沒有設備,這是值得商榷的。我個人不會擺脫if宣告和第二個print。我會在不同的區域清理這段代碼:
# `server` is renamed to `device`,
# so that the same thing doesn't have two different names.
# I'd also change `each` to something meaningful.
for each in data:
if "devices" not in each:
print(each["version"], None)
continue
for device in each["devices"]:
print(each["version"], device["host_name"])
uj5u.com熱心網友回復:
另一種解決方案是使用串列推導。較短但可讀性較差。讓我們從簡單的情況開始:如果沒有設備,則列印版本:
[print(row['version']) for row in data if 'devices' not in row]
但是使用嵌套串列理解,事情變得不那么可讀了:
[print(row['version'], [device['host_name'] for device in row['devices']]) for row in data if 'devices' in row]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/418715.html
標籤:
