我有一個數據變量在Python中,我不知道訪問元素。
這裏是數據結構示例:訪問python數據結構
('deploy_with_config', [{'port': 80, 'name': 'test1', 'address': '0.0.0.0'}, {'port': 80, 'name': 'test2', 'address': '0.0.0.0'}])
該數據必須在一個文本文件,每一行進入。
對於這個例子:
TEST1 0.0.0.0 80
TEST2 0.0.0.0 80
我有一個數據變量在Python中,我不知道訪問元素。
這裏是數據結構示例:訪問python數據結構
('deploy_with_config', [{'port': 80, 'name': 'test1', 'address': '0.0.0.0'}, {'port': 80, 'name': 'test2', 'address': '0.0.0.0'}])
該數據必須在一個文本文件,每一行進入。
對於這個例子:
TEST1 0.0.0.0 80
TEST2 0.0.0.0 80
所以,你有一個元組(不可變列表),你可以索引到。你想要元組中的第二項,所以你可以調用[1]。這是一個詞典列表,每個詞都由大括號{}分開。要調用字典中的項目,請使用方括號並調用字典鍵(':'左側的單詞)。這會給你相應的值「test1」等。
如果你不清楚代碼是如何工作的,請遍歷每個階段並遍歷元組的第一個元素,然後通過字典循環播放調用語法。
a = ('deploy_with_config', [{'port': 80, 'name': 'test1', 'address': '0.0.0.0'}, {'port': 80, 'name': 'test2', 'address': '0.0.0.0'}])
for some_dict in a[1]:
print(some_dict["name"], some_dict["address"], some_dict["port"])
使用'dict'這樣的保留名稱作爲變量名是不鼓勵的,因爲這裏它影響了整個['dict'](https://docs.python.org/3.6/library/) stdtypes.html#dict)類。 –
沒有注意到,但你是對的 – TLOwater
你的數據結構是一個元組,由一個串和一個列表的。該列表本身包含字典,每個字典都有3個鍵值對。
你可以找到這類信息是這樣的:
>>> unknown_data = ('deploy_with_config', [{'port': 80, 'name': 'test1', 'address': '0.0.0.0'}, {'port': 80, 'name': 'test2', 'address': '0.0.0.0'}])
>>> type(unknown_data)
<class 'tuple'>
>>> type(unknown_data[0])
<class 'str'>
>>> type(unknown_data[1])
<class 'list'>
>>> type(unknown_data[1][0])
<class 'dict'>
爲了讓您建議的輸出格式,你可以這樣做:
for item in unknown_data[1]:
print('{0[name]} {0[address]} {0[port]}'.format(item))
假設數據是一個元組
data = ('deploy_with_config', [{'port': 80, 'name': 'test1', 'address': '0.0.0.0'}, {'port': 80, 'name': 'test2', 'address': '0.0.0.0'}])
params = data[1]
params = [" ".join([item['name'], item['address'], str(item['port'])]) for item in params]
with open('data.txt') as fw:
fw.writelines(params)
你嘗試過這麼遠嗎? – FLab
問題還不清楚...詳細說明 –