python - 有没有办法在每次执行 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
对此的新手,所以任何帮助将不胜感激:)
解决方案
你需要这样的东西:
for dog_name in dog_names:
new_dog_info = info(
name = dog_name,
exercise = randint(0, 100),
...
如果这是一个家庭作业,你可能不希望我把它全部写出来。
推荐阅读
- c++ - 有没有办法从 Visual Studio 的控制台窗口中隐藏此消息?
- r - 错误:逻辑索引向量的长度必须为 1
- xml - 使用 xslt 查找重复值并用唯一值替换它们
- c# - 通过jQuery将部分视图调用到Bootstrap Modal?
- grails - 我有最新版本的 grails 3.3.7,但是当我检查 grails -version 时,它仍然显示 2.3.11。另外,我需要升级到 2.5.6。
- python - 在python脚本中获取ifstat值
- xml - 使用 Spark / Scala 从 XML 记录中提取元素
- python - 用两个不同的定界符分割字符串的最佳方法,将两个单词大写,只包含一个定界符,然后重新添加两个定界符?
- jquery - 在 jquery ajax 调用之后,我想重定向到另一个页面并希望在该页面上打印返回的 json 数据
- lyft-api - Lyft Developer API 乘车请求 - 需要额外权限