Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:如何创建if/while循环以继续创建变量/字典_Python_Loops - Fatal编程技术网

Python:如何创建if/while循环以继续创建变量/字典

Python:如何创建if/while循环以继续创建变量/字典,python,loops,Python,Loops,首先,我对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

首先,我对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}
<> P>另一个要考虑的是,学生字典中有一个特定的密钥是可用的。这是一个时间列表(作为整数,所以只有一小时整),它们可以用于我将在一个单独的循环中阅读的内容。进一步说明,就我所知,我需要每本字典中的所有信息保持链接在一起,而不能仅仅制作一本大字典

{first: 'john', last: 'doe', score: 87, availability: [2,3,7,8,9]}
因此,我当然认为,如果“某物”是真的(基本上,当有人仍在输入有关学生的信息,如他们的姓名和成绩等信息时),我需要它来创建一个新变量,并为其分配一个包含所有这些信息的字典(通过一个已经预定义的函数)。一旦“某物”是假的,我会将这些变量编译成一个列表,我已经知道如何做


那么我们到了,非常感谢您的帮助

首先,我建议在学生记录中使用class()而不是字典。从长远来看,类将为代码添加更多的结构。可以把字典想象成一个更“自由形式的查找表”(或者一个哈希表,如果你愿意的话……因为它们就是这样)


我已经开始了一个代码,可以帮助你行动。。 请在下面查看。 如果你有任何问题,尽管问。 我没有写出完整的解决方案。。这里已经过了午夜 您必须更改主函数中的数据文件名/位置

问候,

--代码从这里开始--


对不起,你的问题不是很清楚。请你简化一下好吗?对不起,我知道这太冗长了哈哈,我只是简单地把它放在第二段(“问题:如何创建…”)。你说的“一本大词典不能将信息链接在一起”是什么意思?我将有大量的学生,比如说50名左右。每个人都有自己的姓名、等级、联系信息和唯一的可用性。创建一个包含所有50名学生的所有信息的大词典是否会将这些信息链接到他们所属的特定学生?比如说,如果我有一本包含50个条目的“分数”的大字典,我如何将它们与所属的学生保持链接?你是否考虑将数据保存到磁盘?有文件吗???另一方面,如果您使用一系列字典会怎么样?这些感叹号不是有效的Python语法-使用
而不是
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()