如何只用我的 len() 打印我的字典中的项目一次而不打印数字 9、9 次 [关闭]
Posted
技术标签:
【中文标题】如何只用我的 len() 打印我的字典中的项目一次而不打印数字 9、9 次 [关闭]【英文标题】:How to print out my items in my dictionary only once with my len() without it printing the number 9, 9 times [closed] 【发布时间】:2022-01-19 22:08:46 【问题描述】:如何只用我的 len() 将我的字典中的项目打印一次,而不打印数字 9、9 次。请帮帮我,我想不通。
这是我的代码:
d =
"Brand: ": "Honda",
"model: ": "Pilot",
"year: ": 2021
for x in d:
print(len(d))
ls = ["Chevrolet", "Dodge", "Ford", "Honda", "Jeep", "Nissan", "Saturn", "Subaru", "Tesla", "Toyota"]
for x in ls:
print(len(ls))
ri = raw_input("Enter 'd', if you want to see a dictionary for a car. Or enter 'ls', if you want to see a list of cars: ")
def cars(d, ls):
print ri
if ri == 'd':
print d
if ri == 'ls':
print ls
cars(d, ls)
【问题讨论】:
喜欢print(d)
?
你为什么写for x in d: print(len(d))
?这确实可以满足您的要求。
为什么该代码混合了 python2 和 python3 代码?这是不可能的;)
将for x in d: print(len(d))
更改为for x in d.values(): print(x)
`
也许你想要的是for x in ls: print(len(x))
【参考方案1】:
for x in d: print(len(d))
你有一个 for 循环正在运行,它正在多次打印,将其切换为 print(len(d))
即可修复它
【讨论】:
【参考方案2】:您正在打印len
,这就是您所看到的,更改为您迭代的变量
d = "Brand: ": "Honda", "model: ": "Pilot", "year: ": 2021
for key, val in d.items():
print(key, val)
ls = ["Chevrolet", "Dodge", "Ford", "Honda", "Jeep", "Nissan", "Saturn", "Subaru", "Tesla", "Toyota"]
for x in ls:
print(x)
【讨论】:
【参考方案3】:您的需求未明确。这是我从您的需求中理解的实现。
d =
"Brand: ": "Honda",
"model: ": "Pilot",
"year: ": 2021
ls = ["Chevrolet", "Dodge", "Ford", "Honda", "Jeep", "Nissan", "Saturn", "Subaru", "Tesla", "Toyota"]
ri = raw_input("Enter 'd', if you want to see a dictionary for a car. Or enter 'ls', if you want to see a list of cars: ")
def cars(d, ls):
print(ri)
if ri == 'd':
print(d)
if ri == 'ls':
print(len(ls))
for l in ls:
print(l)
cars(d, ls)
【讨论】:
以上是关于如何只用我的 len() 打印我的字典中的项目一次而不打印数字 9、9 次 [关闭]的主要内容,如果未能解决你的问题,请参考以下文章