数组(python与C语言对比学习)
一、数组定义
在 连续 的内存空间中,存储 相同类型 的元素叫做数组。
二、数组的创建
1.python
a_list = [1, 2, 3]
print(a_list)
2.C语言
#include <stdio.h>
int main()
{
int a[3] = {1, 2, 3};
int count = 3;
for (size_t i = 0; i < count; i++)
{
printf("%d\n", a[i]);
}
return 0;
}
int main()
{
char a_list[] = {'a','b','c','\0'};
printf("%s",a_list);
return 0;
}
二、数组元素的插入
1.python
a_list.append(4)
a_list.append(5)
print(a_list)
a_list.insert(3, 99)
print(a_list)
2.C语言
#include <stdio.h>
int count = sizeof(a_list) / sizeof(a_list[0]);
int index = 2;
int insert = 50;
int b_list[count + 1];
for (size_t i = 0; i <= count; i++)
{
if (i < index)
{
b_list[i] = a_list[i];
}
else if (i == index)
{
b_list[i] = insert;
}
else
{
b_list[i] = a_list[i - 1];
}
}
count++;
printf("B_count = %d\n", count);
for (size_t i = 0; i < count; i++)
{
printf("b%d=%d\n", i, b_list[i]);
}
return 0;
三、数组的访问
1.python
temp = a_list[2]
print(temp)
2.C语言
int temp = b_list[3];
printf("b3=%d",temp);
四、数组元素更新
python
a_list[2] = 108
print(a_list)
C语言
b_list[2]=108;
五、数组元素删除
python
a_list.remove(108)
print(a_list)
a_list.pop(2)
print(a_list)
a_list.pop()
print(a_list)
C语言
#include <stdio.h>
int main()
{
int a_list[] = {1, 2, 108, 99, 4, 5};
int del_index=3;
int count = sizeof(a_list)/sizeof(a_list[1]);
int b_list[count-1];
for (size_t i = 0; i < count; i++)
{
if (i < del_index-1)
{
b_list[i] = a_list[i];
}
else
{
b_list[i] = a_list[i+1];
}
}
printf("B_count = %d\n", count-1);
for (size_t i = 0; i < count-1; i++)
{
printf("b%d=%d\n", i, b_list[i]);
}
}
————————————————————————————————————————————————————————————————
#include <stdio.h>
int main()
{
int a_list[] = {1, 2, 108, 99, 4, 5};
int del_num = 99;
int count = sizeof(a_list) / sizeof(a_list[1]);
int b_list[count - 1];
int i, j = 0;
while (i < count)
{
if (a_list[i] == del_num)
{
i++;
}
b_list[j]=a_list[i];
j++;
i++;
}
printf("B_count = %d\n", count - 1);
for (size_t i = 0; i < count - 1; i++)
{
printf("b%d=%d\n", i, b_list[i]);
}
}
六、巩固练习
例题来自力扣第一题:两数之和
python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
d = {}
for i,e in enumerate(nums):
if target -e in d:
return [i,d.get(target-e)]
d[e] = i
C语言
int* twoSum(int* nums, int numsSize, int target, int* returnSize)
{
int map[2*numsSize];
for (size_t i = 0; i < numsSize; i++)
{
map[2*i] = nums[i];
map[2*i+1] = i;
}
int j,m;
for (size_t i = 0; i < numsSize; i++)
{
j = target - nums[i];
m = 2*i+2;
while (m < 2*numsSize)
{
if (j == map[m] && map[m+1] != i)
{
int* ret = malloc(sizeof(int) * 2);
ret[0] = i, ret[1] = map[m+1];
*returnSize = 2;
return ret;
}
m = m+2;
}
}
return 0;
}
人生苦短,我用python
|