我有一長串 100 多個唯一(名稱不重復)鍵/值對的串列,我想將它們合并為兩個等寬的列。
- 如何獲得下一次迭代的鍵/值?(即如何在同一迭代中列印兩個鍵/值對?)
- 如何讓對以 40 個字符寬度的兩列或一對最長長度的最大寬度列印?
電流回路:
for key in example:
print(f'{key}: {example[key]}')
示例字典:
example = {
'key0': 'val0',
'key1': 'val1',
'key2': 'val2',
'key3': 'val3',
'key4': 'val4',
'key5': 'val5'
}
期望的結果:
key0: val0 key1: val1
key2: val2 key3: val3
key4: val4 key5: val5
uj5u.com熱心網友回復:
您可以兩個兩個地遍歷鍵串列
keys = list(example.keys())
for i in range(0,len(keys),2):
key1 = keys[i]
key2 = keys[i 1]
print("%s:%s %s:%s"%(key1,example[key1],key2,example[key2]))
輸出:
key0:val0 key1:val1
key2:val2 key3:val3
key4:val4 key5:val5
uj5u.com熱心網友回復:
請不要問兩個不同的問題。我只會回答如何以您想要的方式遍歷字典。還有很多其他問題可以解釋如何格式化為固定寬度的欄位。
用于itertools.islice()對字典的奇數和偶數元素進行切片,然后將zip()它們配對。
from itertools import islice, zip_longest
for (key1, value1), (key2, value2) in \
zip_longest(islice(example.items(), 0, None, 2),
islice(example.items(), 1, None, 2),
fillvalue = (None, None)):
if key2 is not None:
print(f'{key1}: {value1} {key2: value2}')
else:
print(f'{key1}: {value1}')
uj5u.com熱心網友回復:
這有效:
example = {
"key0": "val0",
"key1": "val1",
"key2": "val2",
"key3": "val3",
"key4": "val4",
"key5": "val5",
}
max_width = max([len(f"{k}: {v}") for k, v in example.items()])
column_width = max(40, max_width)
keys = list(example.keys())
values = list(example.values())
for i in range(0, len(keys) - 1, 2):
left_key = keys[i]
right_key = keys[i 1]
left_value = values[i]
right_value = values[i 1]
n_spaces = column_width - len(f"{left_key}: {left_value}")
print(f"{left_key}: {left_value}" " " * n_spaces f"{right_key}: {right_value}")
uj5u.com熱心網友回復:
另一種方法:
from itertools import zip_longest
i = iter(example.items())
for col1, col2 in zip_longest(i, i):
col1 = f"{col1[0]}: {col1[1]}"
col2 = f"{col2[0]}: {col2[1]}" if col2 else ""
print(f"{col1:<40} {col2:<40}")
印刷:
key0: val0 key1: val1
key2: val2 key3: val3
key4: val4 key5: val5
uj5u.com熱心網友回復:
如果您想將格式化資料列印到控制臺,也許使用豐富的庫?
from rich.console import Console
from rich.table import Table
from itertools import zip_longest
console = Console()
table = Table(show_header=False)
lst = iter(example.items())
for (k1, v1), (k2, v2) in zip_longest(lst, lst, fillvalue=("", "")):
table.add_row(k1, v1, k2, v2)
console.print(table)
輸出(在實際控制臺上看起來更好......):
┏━━━━━━┳━━━━━━┳━━━━━━┳━━━━━━┓
┃ key0 ┃ val0 ┃ key1 ┃ val1 ┃
│ key2 │ val2 │ key3 │ val3 │
│ key4 │ val4 │ key5 │ val5 │
│ key6 │ val6 │ │ │
└──────┴──────┴──────┴──────┘
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/490921.html
