ในแบบฝึกหัดที่ 39 ของ Learn Python The Hard Way บรรทัดที่ 37 ถึง 39 มีลักษณะดังนี้:
print "-"*10
for state, abbrev in states.items():
print "%s has the city %s" % (state, abbrev)
ฉันคิดว่าฉันเข้าใจสิ่งนี้ ฉันคิดว่า Python รับ KEY:VALUE จาก "states" และกำหนด KEY ให้กับ "state" และ VALUE เป็น "abbrev"
อย่างไรก็ตาม ฉันพบว่ามีสิ่งแปลก ๆ เกิดขึ้นเมื่อฉันป้อนรหัสต่อไปนี้:
print "-"*10
for test in states.items():
print "%s has the city %s" % (test)
มันสร้างผลลัพธ์เดียวกันกับรหัสต้นฉบับ แต่จะใช้งานได้ก็ต่อเมื่อคุณใส่ %s
ลงในคำสั่ง print สองครั้ง
ใครสามารถอธิบายสิ่งที่เกิดขึ้นกับ "การทดสอบ" ได้บ้าง "การทดสอบ" คืออะไรกันแน่? ทูเพิลหรือเปล่า? ดูเหมือนว่าจะมีทั้ง KEY
และ VALUE
จาก states.items()
ฉันได้ดูคำถามอื่นๆ ในแบบฝึกหัดที่ 39 ที่นี่แล้ว และไม่พบคำถามเดียวกัน
รหัสแสดงอยู่ด้านล่าง (สำหรับ Python 2.7)
# create a mapping of state to abbreviation
states = {
'Oregan': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York' : 'NY',
'Michigan' : 'MI'
}
print "-"*10
for state, abbrev in states.items():
print "%s has the city %s" % (state, abbrev)
print "-"*10
for test in states.items():
print "%s has the city %s" % (test)