【问题标题】:For-Loop printing entire rangeFor-Loop 打印整个范围
【发布时间】:2018-06-20 19:29:45
【问题描述】:

我是 Python 新手,正在学习 For 循环并编写了以下代码:

cars = [1, 2, 3, 4]
trucks = ['red', 'blue', 'green', 'white']

for numbers in cars:
    print (f"I can count: {numbers}")

for colors in trucks:
    print(f"I can list colors: {colors}")

new_list = []

for numbers in range(0, 4):
    new_list.append(numbers)

for numbers in new_list:
    print(f"I can count more: {new_list}!")

我得到了这个结果:

I can count: 1
I can count: 2
I can count: 3
I can count: 4
I can list colors: red
I can list colors: blue
I can list colors: green
I can list colors: white
I can count more: [0, 1, 2, 3]!
I can count more: [0, 1, 2, 3]!
I can count more: [0, 1, 2, 3]!
I can count more: [0, 1, 2, 3]!

对于“我可以计算更多”部分,我如何让它按数字顺序列出范围:

I can count more: 1! 
I can count more: 2!, etc.

而不是打印行中的整个范围?

【问题讨论】:

  • 传递 {numbers} 而不是 {new_list}?
  • 您还可以将new_list 简化为new_list = range(4)

标签: python for-loop range


【解决方案1】:
print(f"I can count more: {new_list}!")

应该是

print(f"I can count more: {numbers}!")

因为new_list 是整个列表,而numbers 是您在for numbers in new_list 中定义的for 变量

【讨论】:

  • 也应该是number 而不是numbers。否则世界上所有的学究都会抱怨:-)
  • 我只是关注问题变量名称@paxdiablo
【解决方案2】:

使用“数字”而不是“new_list”。并且不要在同一个列表上一次又一次地迭代,因为 new_list 包含您在最后一个循环中显示的相同项目。所以,你的代码应该是这样的,

for numbers in range(0, 4):
    print(f"I can count more: {numbers}!")

【讨论】:

    猜你喜欢
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 2014-09-21
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    相关资源
    最近更新 更多