[英]How to populate a 2-d array in python?
What's the pythonic way to rewrite the following C code? 重写以下C代码的pythonic方法是什么?
int a[16][4];
int s[16] = {1,0,2,3,0,1,1,3,3,2,0,2,0,3,2,1};
for (int i = 0; i < 16; ++i) {
for (int j = 0; j < 16; ++j) {
int diff = i ^ j;
int val = s[i] ^ s[j];
++a[diff][val];
}
}
Here is some equivalent Python code: 这是一些等效的Python代码:
a = [[0]*4 for i in range(16)]
s = [1,0,2,3,0,1,1,3,3,2,0,2,0,3,2,1]
for i in range(16):
for j in range(16):
diff = i ^ j
val = s[i] ^ s[j]
a[diff][val] += 1
The array is initialized by 该数组由初始化
In [1]: a=[[0]*4]*16
In [2]: a
Out[2]:
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
Then the second array (list): 然后第二个数组(列表):
In [5]: s = [1,0,2,3,0,1,1,3,3,2,0,2,0,3,2,1]
Bitwise operators in Python are similar to C. As FJ already posted it's the same. Python中的按位运算符类似于C。正如FJ已经发布的一样。
Implementation 履行
a = [[0]*4 for _ in range(16)]
s = [1,0,2,3,0,1,1,3,3,2,0,2,0,3,2,1]
from itertools import product
for diff, val in ((i ^ j, s[i] ^ s[j])
for i, j in product(range(16), repeat = 2):
a[diff][val] += 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.