items = ['Item 1', 'Item 2', 'Item 3']
new_items = {'bacon': items, 'bread': items, 'cheese': items}
for key, value in new_items.items():
print('{}: {}'.format(key, *value))
輸出:
bacon: Item 1
bread: Item 1
cheese: Item 1
如何列印所有專案?如果我在value列印所有 3 個專案之前洗掉星號,但在方括號中。
uj5u.com熱心網友回復:
問題簡化為“如何將串列轉換為字串?”。一些可能適合您的選項:
In [1]: items = ['Item 1', 'Item 2', 'Item 3']
In [2]: ' '.join(items)
Out[2]: 'Item 1 Item 2 Item 3'
In [3]: ', '.join(items)
Out[3]: 'Item 1, Item 2, Item 3'
uj5u.com熱心網友回復:
您可以在format()方法呼叫中創建要輸出的字串:
items = ['Item 1', 'Item 2', 'Item 3']
new_items = {'bacon': items, 'bread': items, 'cheese': items}
for key, values in new_items.items():
print('{}: {}'.format(key, ', '.join(values)))
輸出:
bacon: Item 1, Item 2, Item 3
bread: Item 1, Item 2, Item 3
cheese: Item 1, Item 2, Item 3
uj5u.com熱心網友回復:
我認為您的問題在于您如何構建new_items. 試試這個,然后列印:
items = ['Item 1', 'Item 2', 'Item 3']
labels = ['bacon', 'bread', 'cheese'}
new_items = zip(labels, items)
uj5u.com熱心網友回復:
使用f 字串:
items = ['Item 1', 'Item 2', 'Item 3']
new_items = {'bacon': items, 'bread': items, 'cheese': items}
for key, value in new_items.items():
print(f'{key}: {", ".join(value)}')
輸出:
bacon: Item 1, Item 2, Item 3
bread: Item 1, Item 2, Item 3
cheese: Item 1, Item 2, Item 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/324844.html
下一篇:如何在串列中創建字典
