我是Python的新手,學習了For Loops并編寫了以下代碼: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: 1I can count: 2I can count: 3I can count: 4I can list colors: redI can list colors: blueI can list colors: greenI can list colors: whiteI 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.而不是打印行中的整個范圍?
2 回答

慕妹3146593
TA貢獻1820條經驗 獲得超9個贊
print(f"I can count more: {new_list}!")
應該
print(f"I can count more: {numbers}!")
因為new_list
是整個列表,并且numbers
是您for
在中定義的變量for numbers in new_list

人到中年有點甜
TA貢獻1895條經驗 獲得超7個贊
使用“數字”代替“ new_list”。并且不要在同一列表上一次又一次地迭代,因為new_list包含您在上一個循環中顯示的相同項目。所以,您的代碼應該是這樣的,
for numbers in range(0, 4):
print(f"I can count more: {numbers}!")
添加回答
舉報
0/150
提交
取消