Есть ли способ изменить переменную каждый раз, когда выполняется цикл for? - PullRequest
0 голосов
/ 17 января 2019

Я не знаю, как создать новую переменную для каждого нового имени из списка, используя цикл for.

Поскольку я новичок в этой области кодирования, я занимался небольшим школьным проектом, пытался сократить свой код и столкнулся с небольшой проблемой длинного списка, который у меня был. Поэтому я попытался поместить его в цикл for, чтобы для каждого другого имени (странно данного имени собаки) в списке я мог получить новую переменную для него, но просто застрял. Кто-нибудь может придумать решение?

import random

class info():

    def __init__(self, name, exercise, intel, friend, drool):
        self.name = name
        self.exercise = exercise
        self.intel = intel
        self.friend = friend
        self.drool = drool


    def __repr__(self):
        return "\nName : {}\na-Exercise : {}\nb-Intelligence : {}\nc-Friendliness : {}\nd-Drool : {}".format(
            self.name, self.exercise, self.intel, self.friend, self.drool)

dog_names = ["Annie the Afgan Hound", "Bertie the Boxer", "Betty the Borzoi", "Charlie the Chihuahua", "Chaz the Cocker Spaniel", "Donald the Dalmatian", "Dottie the Doberman", "Fern the Fox Terrier", "Frank the French Bulldog", "George the Great Dane", "Gertie the Greyhound", "Harry the Harrier", "Ian the Irish Wolfhound", "Juno the Jack Russell", "Keith the Kerry Blue", "Larry the Labrador", "Marge the Maltese", "Max the Mutt", "Nutty the Newfoundland", "Olive the Old English Sheepdog", "Peter the Pug", "Poppy the Pekingese", "Rosie the Rottweiler", "Ruby the Retriever", "Sam the Springer Spaniel", "Sukie the Saluki", "Vernon the Vizsla", "Whilma the West Highland Terrier", "William the Whippet", "Yolande the Yorkshire Terrier"]

#This is what i want to shorten

a = info("Annie the Afgan Hound", random.randint(1, 5), random.randint(1, 100), random.randint(1, 10), random.randint(1, 10))#1

b = info("Bertie the Boxer", random.randint(1, 5), random.randint(1, 100), random.randint(1, 10), random.randint(1, 10))
#etc

Я хотел бы создать «карточку» для каждого имени; так что каждый раз, когда запускается этот код, для каждого имени появляется новая переменная. Например ...

a = Name:Annie the Afgan Hound |
    Exersice:10 |
    Intelligence:34 |
    Friendliness:4 |
    Drool:2

b = Name:Bertie the Boxer |
    Exersice:7 |
    Intelligence:87 |
    Friendliness:9 |
    Drool:10

Новое в этом, поэтому любая помощь будет оценена :)

Ответы [ 2 ]

0 голосов
/ 17 января 2019

Вы почти наверняка захотите поместить их в список:

kennel = []
for name in dog_names:
    kennel.append(info(name,
                       random.randint(1, 5), 
                       random.randint(1, 100),
                       random.randint(1, 10),
                       random.randint(1, 10)))

Когда вы закончите этот цикл, у вас будут все ваши info объекты в этом списке, и вы сможете легко перебирать этот список.

for dog in kennel:
    ...
0 голосов
/ 17 января 2019

Вам нужно что-то вроде этого:

for dog_name in dog_names:
    new_dog_info = info(
        name = dog_name,
        exercise = randint(0, 100),
        ...

Если это домашнее задание, вы, вероятно, не хотите, чтобы я все это выписывал.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...