首页 > 解决方案 > 有没有办法在每次执行 for 循环时更改变量?

问题描述

我不知道如何使用 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

对此的新手,所以任何帮助将不胜感激:)

标签: pythonfor-loop

解决方案


你需要这样的东西:

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

如果这是一个家庭作业,你可能不希望我把它全部写出来。


推荐阅读