首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >有没有可能使这个python for循环更简单?

有没有可能使这个python for循环更简单?
EN

Stack Overflow用户
提问于 2021-04-05 18:50:56
回答 1查看 37关注 0票数 0

我对编程非常陌生,我正在通过python速成班学习Python。我想知道是否有办法使打印语句更简单、更短?

代码语言:javascript
复制
father = {'age': 26, 'skin': 'dark', 'complexity': 'tall'}  

mother = {'age': 30, 'skin': 'white', 'complexity': 'small'}

sister = {'age': 15, 'skin': 'white', 'complexity': 'tall'}

people = [father, mother, sister]  # stored 3  dictionaries inside a list

for character in range(1): # loop the list in range function, loop once 

   print(f"\nMy fathers age is: {father['age']}, skin is: {father['skin']}, complexity: {father['complexity']}")
   print("")
   print(f"\nMy mothers age is: {mother['age']}, skin is: {mother['skin']}, complexity: {mother['complexity']}")
   print("")
   print(f"\nMy sisters age is: {sister['age']}, skin is: {sister['skin']}, complexity: {sister['complexity']}")
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-05 19:40:57

如果允许将people类型更改为dict,则可以这样做:

代码语言:javascript
复制
father = {'age': 26, 'skin': 'dark',  'complexity': 'tall'}
mother = {'age': 30, 'skin': 'white', 'complexity': 'small'}
sister = {'age': 15, 'skin': 'white', 'complexity': 'tall'}

people = {
    "father": father,
    "mother": mother,
    "sister": sister
}

for name in people:
    data = ", ".join([f"{k} is: {v}" for k, v in people[name].items()])
    print(f"My {name}'s", data)

我们在这里要做的是,迭代字典people (按其键作为name),在for loop中迭代子字典(父亲、母亲、姐妹),并使用inline for loop根据它们的键值对来创建字符串,最后将它们与", "连接起来,并将产生的字符串分配给变量data。然后,打印人的名字和数据

如果不允许更改people类型,则可以这样做:

代码语言:javascript
复制
people = [father, mother, sister]
names = ["father", "mother", "sister"]

for i in range(len(people)):
    data = ", ".join([f"{k} is: {v}" for k, v in people[i].items()])
    print(f"My {names[i]}'s", data)

在这里,我们只是按列表索引进行迭代。

产出将相同:

代码语言:javascript
复制
My father's age is: 26, skin is: dark, complexity is: tall
My mother's age is: 30, skin is: white, complexity is: small
My sister's age is: 15, skin is: white, complexity is: tall
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66958201

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档