python和golang对比系列(一)–流程控制循环
一、 条件循环
- golang的条件循环表达式
// 循环表达式
for 初始语句; 条件表达式; 结束语句{
循环体代码
}
// 例如:
for i:=0; i<=10; i++{
println(i)
}
- Python的条件循环表达式
# 循环表达式
while 条件表达式:
循环体代码
# 例如:
i = 0
while i<=10:
print(i)
i++
二、for的键值遍历
- golang : for key, value := range 对象
Go语言可以使用 for range 遍历数组、切片、字符串、map和通道(channel)。
对象 | key | value |
---|---|---|
数组、切片 | 索引 | 元素 |
字符串 | 索引 | 字符(rune类型,int32) |
map | 键 | 值 |
通道(channel) | 无 | 管道内的类型对应的数据 |
// for range 遍历
testList := []int{1,3,5}
for key, value := range testList {
println(key, value)
}
- python : for item in 对象
python中的 for 循环会访问一个可迭代对象(序列或迭代器)中的所有元素。
2.1 遍历序列
# 遍历数组
testList = [1, 3, 5]
for item in testList:
print(item)
# 遍历字符串
test_str = "helloworld"
for item in test_str :
print(item )
# 使用项和索引迭代
nameList = ["Tom", "Jack", "Rose"]
for i, name in enumerate(nameList):
print(i)
print(name)
# 遍历字典
testDict = {
"1": 1,
"2": 2,
"3": 3
}
for key, value in testDict.items():
print(key)
print(value)
2.2 遍历迭代器
python实现传统伪条件设置下使用 for 声明:
# 传统伪条件设置下使用 for
for value in range(0, 10):
print(value )