python 对列表中任意两个数进行操作 (python operate any two elements in list)
python中, 实现列表中的整型元素两两相乘或列表中的数组元素两两相与
1. 假设列表中的元素是整型, 可调用以下函数:
1 def list_any_two_mul(mylist):
2 num = 1
3 temp = []
4 for i in mylist[:-1]:
5 temp.append([i * j for j in mylist[num:]])
6 num = num + 1
7 # 把多个列表变成只有一个列表
8 results = [y for x in temp for y in x]
9 return results
假设有列表 mylist = [3, 5, 6, 8], 调用了以上的函数 list_any_two_mul(mylist) 则返回 [15, 18, 24, 30, 40, 48]
2. 假设列表中的元素是数组形式, 可以调用以下函数:
1 def list_any_two_and(mylist2):
2 temp2 = []
3 num2 = 1
4 # 先对列表中的元素两两相与
5 for i in mylist2[:-1]:
6 temp2.append([cv2.bitwise_and(i, j) for j in mylist2[num2:]])
7 num2 = num2 + 1
8
9 # 再把相与后的结果放在一个列表中
10 results2 = []
11 for i in range(len(temp2)):
12 for j in range(len(temp2[i])):
13 results2.append(temp2[i][j])
14 return results2
验证以上函数, 先生成元素是数组的列表,再调用函数, 具体实现可参照如下代码:
>>> import numpy as np
>>> a=np.arange(1,13).reshape(3,4)
>>> a
>>> array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
>>> b=np.arange(13,25).reshape(3,4)
>>> b
>>> array([[13, 14, 15, 16],
[17, 18, 19, 20],
[21, 22, 23, 24]])
>>> c=np.random.randint(0,2,(3,4))
>>> c
>>> array([[0, 1, 1, 1],
[0, 0, 1, 1],
[0, 0, 1, 1]])
>>> d=[a,b,c]
>>> g=list_any_two_and(g)
>>> g
>>> [array([[1, 2, 3, 0],
[1, 2, 3, 0],
[1, 2, 3, 8]], dtype=int32), array([[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 1, 0]], dtype=int32), array([[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 1, 0]], dtype=int32)]
本人水平有限, 期待有更好更简便的方法, 有错误欢迎指正, 谢谢.