我对编程非常陌生,我正在通过python速成班学习Python。我想知道是否有办法使打印语句更简单、更短?
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']}")发布于 2021-04-05 19:40:57
如果允许将people类型更改为dict,则可以这样做:
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类型,则可以这样做:
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)在这里,我们只是按列表索引进行迭代。
产出将相同:
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: tallhttps://stackoverflow.com/questions/66958201
复制相似问题