[英]Creating a list of tuples from a function
我對python相當陌生,但是我已經是該語言的忠實擁護者,我目前正在研究一些教程,並且進行了大量閱讀,並嘗試應用我所閱讀的內容。
使用該網站已有一段時間,但這是我第一次發布
我正在解決一個問題,該問題要求我修改一個函數,以便返回元組列表。 我已經嘗試了我所知道的一切,但沒有獲得任何成功,這是我所獲得的。
這是我的功能:
def ask_age ():
newList=[]
count = int (input( "Enter Count "))
if count >7:
count=7
for n in range (count):
age = int(input( "Please Enter age = " ))
if age > 0:
newList.append(age)
print ("You are", age, "years old")
if age < 16:
print ("This is a child")
elif age >= 18:
print ("This is an Adult")
else:
print ("This is a youth")
print(newList)
當我跑步時:
ask_age()
這就是結果
輸入計數4
請輸入年齡= 15
您今年15歲,這是一個孩子
請輸入年齡= 17
你今年17歲這是一個青年
請輸入年齡= 18
您是18歲,這是成人
請輸入年齡= 25
您今年25歲,這是成人
[15、17、18、25]
如前所述,我現在需要修改函數,以便返回元組列表,如下所示:
[(15, 'This is a child'), (17, 'This is a youth'), (18, 'This is an Adult'), (25, 'This is an Adult')]
任何幫助將不勝感激
改變現在的部分
if age > 0:
newList.append(age)
print ("You are", age, "years old")
if age < 16:
print ("This is a child")
elif age >= 18:
print ("This is an Adult")
else:
print ("This is a youth")
改為:
if age > 0:
if age < 16:
newList.append((age, "This is a child"))
elif age >= 18:
newList.append((age, "This is an Adult"))
else:
newList.append((age, "This is a youth"))
而最后的print(newList)
將return newList
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.