我剛剛學習Python與電子書的Python中的一個字節和一些YouTube教程。我已經達到For循環語句。它不是我不明白它,但初學者的例子只顯示:「我在範圍內...」我的問題是爲什麼只有'在範圍'選項給出。我知道這個陳述,無論是範圍還是範圍,都是如此。但是,還有其他選擇,而不是範圍? 你能給我一個簡單的使用for循環的語法嗎?他們沒有在這本電子書中。如果我感到煩躁和困惑,謝謝並抱歉。我只是自己學習。For循環在python編程?
1
A
回答
3
當然,有很多方法可以使用for循環。 for i in range()
通常用於循環某些特定次數的事物,或者只是用計數器重複執行某些操作。
事實上,你甚至不必遍歷列表。您可以通過遍歷字符串:
>>> for char in 'hello':
... print char
...
h
e
l
l
o
甚至一本字典:
>>> for key in {'foo':'bar','cabbage':'cake'}:
... print key
...
cabbage
foo
2
Python沒有典型的循環構建一個像Java,C,C的 「C系列」 語言++,等等。 Python不是唯一這樣做的腳本語言(我相信bash也是這樣做的,但不要引用我)。如果你想要的東西真格的,可以是「正常」的循環(和我假設你做的):
for(int i = 0; i < n; i++){ /* do something */ }
我建議在Python
i = 0
while (i < n) :
// do something
或使用while循環xrange
for i in xrange(0, n) :
// do something
x範圍是很像的範圍,但它不同時存儲所有的值:http://docs.python.org/2/library/functions.html#xrange
我個人會使用xrange,我不知道更好的解決方案。祝你好運!
相關問題
- 1. 如何在python中編寫for循環
- 2. Python - For循環
- 3. Python for循環?
- 4. Python編程循環
- 5. 對於在for循環Python的循環
- 6. 在for循環中編寫while循環
- 7. for循環中的線程在Python 3
- 8. Python - np.dot for for循環
- 9. randrange for python 3.5 for循環
- 10. For循環條件在Python
- 11. 在Python中的for循環
- 12. 的Python - 平在for循環
- 13. 的Python:在for循環
- 14. for循環在c + +和python
- 15. Python Json for循環
- 16. 的Python for循環
- 17. For循環Python的
- 18. Python中,for循環
- 19. 的Python for循環
- 20. Python for循環與?
- 21. for循環中的編碼排除(python)
- 22. 在for循環中遞歸運行for循環(python)
- 23. Python編程無意循環
- 24. for循環不夠循環 - Python
- 25. python for循環和理解循環
- 26. Python for循環跳過其他循環?
- 27. python while循環和for循環
- 28. Python雙循環? while和for循環?
- 29. python進程for循環的問題
- 30. for循環在Sql過程
'range'只是一個返回迭代器的內置函數。你可以遍歷任何可迭代的對象(例如'for file_object中的行,'dictionary中的key','list中的元素'','string中的字符'')。你可以把python的'for'想象成其他語言的'foreach'。請注意,如果你想訪問index和元素,你可以使用'enumerate':'索引,元素枚舉(迭代)'。 – Bakuriu