3 回答

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
正如其他人告訴你的那樣,你正在迭代字典,并且在每次迭代中,鍵和值都會(huì)被替換并打印在新行中。
如果你想使用字典在一行中打印,你可以嘗試將字典轉(zhuǎn)換為數(shù)組并使用 format 方法打印。
Emm = {
'name' : 'Emmylou',
'graduate' : 'Fall 2021',
'bill' : 'paid',
'major' : 'Archeology',
'clubs-' : 'Photography, Acting and Glee'
}
items = []
for (key, value) in Emm.items():
items = items + [key, value]
print("Her {} is {} and she is on track to {} in {}; Her {} is {}; Her {} is {}; She belongs to these school {} {}".format(*items))

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊
首先,我假設(shè)您實(shí)際上已經(jīng)在代碼中縮進(jìn)了 print 語句,否則它根本無法工作。
問題是,對(duì)于每個(gè)循環(huán),您都在所有位置填寫相同的鍵/值對(duì)。
根據(jù)目的,您可以通過執(zhí)行以下操作來獲得聲明:
Emm = {'name' : 'Emmylou', 'graduate' : 'Fall 2021', 'bill' : 'paid', 'major' : 'Archeology', 'clubs-' : 'Photography, Acting and Glee'}
print(f"Her name is {Emm['name']} and she is on track to graduate in {Emm['graduate']}; Her major is {Emm['major']}; Her clubs - is {Emm['clubs-']}")
迭代字典時(shí)可能面臨的另一個(gè)問題是,除非使用 python 3.7 或更高版本,否則無法保證項(xiàng)目在字典中保存的順序。因此,您的鍵/值對(duì)可能不會(huì)按照它們進(jìn)入的順序出現(xiàn)。

TA貢獻(xiàn)1942條經(jīng)驗(yàn) 獲得超3個(gè)贊
在您的代碼中,您將迭代數(shù)據(jù)中的每個(gè)鍵值對(duì);因此,您最終打印了 5 次,每次都使用一個(gè)鍵值對(duì),而不是打印 1 次,每次都使用所有鍵值對(duì)。
嘗試這個(gè)。
Emm = [
('name', 'Emmylou'),
('graduate', 'Fall 2021'),
('bill', 'paid'),
('major', 'Archeology'),
('clubs-', 'Photography, Acting and Glee'),
]
flat_items = [item for pair in Emm for item in pair]
print("Her {} is {} and she is on track to {} in {}; Her {} is {}; Her {} is {}; She belongs to these school {} {}".format(*flat_items))
添加回答
舉報(bào)