交换元素内容
很多语言中元素交换需要引入暂时变量,或者使用Google算法,C++示例如下:
//暂变量(旋转门算法)
int a = 1 , b = 2;
cout << a << “ “ << b;
int tem = 0;
tem = a;
a = b;
b = tem;
cout << a << " " << b;
//加减算法(Google算法)
int a = 1 , b = 2;
a = a + b;
a = a - b;
但是这两种算法都显得很不“优雅”,我们的Python就高级一点了:
num1 = 1
num2 = 2
num1, num2 = num2, num1
Grace !
遍历修改列表元素
可能学习过C-Style语言的读者尝试遍历修改列表的每一个元素时会想当然的把C-Style的For循环修改一下应用在Python身上,举个例子:
//written by C++
#include<iostream>
using namespace std;
int main(){
int arr[6] = {0,1,2,3,4,5};
for (int i=0;i<6;++i){
arr[i]++;
cout<<arr[i];
}
return 0;
}
然后想当然的,写Python就会这样写:
# written by Python3
List = [0,1,2,3,4,5]
for i in List:
i = i+1
print(List)
但是实际上我们会发现这样一顿操作之后列表并没有被修改,实际上这是因为用作替代的 i
代指的是列表中的每一个元素,出代码块之后就失效了,实际上应该这么写:
# written by Python3
List = [0,1,2,3,4,5]
for i in rang(0,len(List)):
List[i] = List[i]+1
print(List)
如此操作, i
代指的就是每一个元素的索引号,其本质上也就和C++完全一样了,读者可以自行敲入两段代码进行比较;
网友评论