简体   繁体   中英

For loops in Dictionaries

I am trying to use a for loop in a dictionary to represent an unknown about of statements that may need to be in the dictionary (based on the specified amount when stating the class). I was wondering what the syntax for that would be if there is any at all.

Earlier today a friend asked me to make a Choose Your Own Adventure game .

  • I wanted to have a random page be the death page.

  • The rest of the pages are story/question pages.

  • I also wanted to have a dictionary that when I put in a page number it returned the type of page it was.

I was trying to use a for statement to get a page number that is called with the class. The pages are random so there is no way for me to know.

from time import sleep
from random import randint

def ClearSys():
  for i in range(0,100):
    print("\n")
class Book:
  def __init__(self,name,pages):

    #self.DeathPage#
    RandomPage=randint(2,pages)
    self.DeathPage=RandomPage
    del RandomPage

    #self.pages#
    self.pages=["Introduction Page"]
    for i in range(2,pages):
      if not i==self.DeathPage:
        self.pages.append("QuestionPage")
      else:
        self.pages.append("DeathPage")



    ####MAIN SECTION I WOULD LIKE TO HIGHLIGHT####
    ##Page number dictionary##
    self.PageNumberToType={
      0:"Introduction Page",
      for i in range(1,len(self.pages)):
        i:self.pages[i]
    }
    ########

I didn't really expect this to work, but I just wrote it out to see if it were possible.

None that I know of; but why does it need to be inside the dictionary literal?

self.PageNumberToType = { 0:"Introduction Page" }

for i in range(1, len(self.pages)):
    self.PageNumberToType[i] = self.pages[i]

Because order is of little importance when it comes to dictionaries, you can do a dictionary-comprehension as well:

self.PageNumberToType = {i: self.pages[i]
                         for i in range(1, len(self.pages[i]))}

self.PageNumberToType.update({0: 'Introduction Page'})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM