我见过这个和这个.我想知道我是否可以在不使用像集合这样的库的情况下完成它,但是使用简单的循环结构.我可以用Python做到这一点吗?
void printRepeating(int arr[], int size)
{
int *count = (int *)calloc(sizeof(int), (size - 2));
int i;
printf(" Repeating elements are ");
for(i = 0; i < size; i++)
{
if(count[arr[i]] == 1)
printf(" %d ", arr[i]);
else
count[arr[i]]++;
}
}
Run Code Online (Sandbox Code Playgroud)
我试过这样做 -
a=[1,2,3,2,4,3,1,7,4,3];
b=[];
for i in a:
b[i]=b[i]+1;
Run Code Online (Sandbox Code Playgroud)
但我明白了
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)
有办法解决吗?
使用dict
(Python的内置哈希映射类型)将是最简单的:
a = [1,2,3,2,4,3,1,7,4,3]
b = {}
for i in a:
# get(key, default) falls back to default if key is not present
b[i] = b.get(i, 0) + 1
> b
{1: 2, 2: 2, 3: 3, 4: 2, 7: 1}
> b[3]
3
Run Code Online (Sandbox Code Playgroud)