[英]Python: How to create an if/while loop to keep creating variables/dictionaries
首先,我對python有一定的了解,但是對它的所有語法了解不多。
問題:如何創建一個if或while循環以繼續創建變量(通過預定義的函數為每個循環分配一個字典)? 或者其他可能更好的主意。 基本上:
if "keep_entering":
#create a new dictionary based on what user inputs
else:
#take all the dictionaries that have been made and put them into a list
#I already have a function to do this though
所以我已經看到了這個問題,但不在我要問的范圍內。 我有一個詞典列表,這是因為我希望該詞典中的某些鍵僅與該特定詞典保持聯系。
例如,每本詞典都是一名學生,在學生詞典中包含代表其姓,名,考試分數等的鍵(基本上是整數和字符串的混合),但顯然我希望這些鍵保持聯系該學生的姓名和其他信息(例如地址或電話號碼)。 然后,我不能只制作一本包含大量名稱和等級等的大詞典,就我所知,它無法將所有信息鏈接在一起。
{first: 'john', last: 'doe', score: 87}
還有一點要考慮的是,學生詞典中有一個特定的密鑰,即可用性。 它是時間的列表(以整數表示,因此僅在一個小時內才出現),它們可用於我將在單獨的循環中閱讀的內容。 進一步說明,據我所知,我需要每個詞典中的所有信息保持鏈接在一起,並且不能僅制作一本大詞典。
{first: 'john', last: 'doe', score: 87, availability: [2,3,7,8,9]}
因此,我當然想出“ / something”是否正確(基本上,當某人仍在輸入有關學生的信息時,例如他們的姓名,年級等信息),我需要它來創建一個新變量,並為其分配一個包含所有內容的字典。此信息(通過已預定義的功能)。 一旦“ something”為假,我將把這些變量中的每一個編譯成一個我已經知道該怎么做的列表。
因此,在這里,我們將非常感謝您的幫助。
首先,我建議使用一個類( https://docs.python.org/2/tutorial/classes.html )而不是用於您的學生記錄的字典。 從長遠來看,一個類將為您的代碼添加更多的結構。 將字典視為一個更“自由形式的查找表”(或者,如果您願意的話,可以使用哈希表,因為這就是它們)。
class Student(object):
def __init__(self, first, last, score):
self.first = first
self.last = last
self.score = score
self.availability = []
def add_availability(self, availability_time):
# make sure it's an integer
if ( not isinstance( availability_time, int ) ):
return False
# check bounds
if ( availability_time < 1 || availability_time > 10 ):
return False
# it checks out, add it up
self.availability.push(availability_time)
return True
然后你的主循環...
students = []
while more_students:
# first = ..logic for first name..
# last = ..logic for last name..
# score = ..logic for score..
stud = Student(first,last,score)
availability_text = ..get input..
while availability_text != 'quit' #change to whatever termination text/method you want
if not stud.add_availability(availability_text):
print 'There was an error!'
availability_text = ..get input..
students.push(stud)
我已經開始編寫代碼,可以幫助您前進。請檢查以下內容。 如有任何疑問,請隨時提出。 我沒有寫完整的解決方案..到了午夜.. :)您將不得不在主要功能中更改數據文件名/位置...
問候,
-代碼從這里開始-
import os
def clrscr_():
os.system('clear') #Check for compatibility with your OS
def prnt_menu():
a = 'z'
while (a not in '01234'):
clrscr_()
print 'Main Menu:\n----------'
print '1 - Print DataBase'
print '2 - Append to DataBase'
print '3 - Edit Item'
print '4 - Delete Item'
print '0 - Exit'
print ''
a = raw_input('Your Choice: ')
return a
def ask_to_create_empty_database_file(fname):
a = 'z'
print ('Would you like me to create empty database file for you?')
while (a not in 'yYnN'):
a = raw_input('(y = yes / n = no)')
if (a in 'yY'):
file(fname, 'w').close()
def print_database(fname, ttl):
if (os.path.isfile(fname)):
clrscr_()
print ' | ',
for it in ttl:
print it, ' | ',
print '\n'
f = file(fname, 'r')
content = f.readlines()
content = [x.strip('\n') for x in content]
f.close()
for ln in content:
print ln
print '\n'
raw_input('Press Enter key to continue!')
else:
print 'Error! Database file does not Exist.'
ask_to_create_empty_database_file(fname)
def append_to_database(fname, ttl):
rVal = []
for it in ttl:
a = raw_input(it + ': ')
rVal.append(a)
f = file(fname, 'a')
f.write(str(rVal))
f.write('\n')
f.close()
print '\n'
raw_input('Press Enter key to continue!')
def main():
file_path = '/path/to/database.dat'
titles_ = ['ID', 'First', 'Last', 'Phone', 'Score', 'Availability']
stop_ = False
while (not stop_):
menu_ = prnt_menu()
if (menu_ == '1'):
print_database(file_path, titles_)
elif (menu_ == '2'):
append_to_database(file_path, titles_)
elif (menu_ == '3'):
#I leave this menu for you :)
pass
elif (menu_ == '4'):
#I leave this menu for you :)
pass
else:
print 'Good Bye! Program exited Safely.\n'
stop_ = True
if __name__ == '__main__':
main()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.