我具有以下功能
import numpy as np
a = [['a','b','c'],['d','e','f'],['g','h','i'],['j','k','l']]
b = np.array(a)
def func01(matrix):
m,n = np.shape(matrix)
for jump in range (m-1):
for row in range (jump):
for col in range (n):
print (matrix[row][col],matrix[row+jump][col])
func01(b)
这导致:
('a','d') (“ b”,“ e”) (“ c”,“ f”) ('a','g') (“ b”,“ h”) ('c','i') ('d','j') ('e','k') ('f','l')
但是我希望我的结果看起来像这样:
('a','d') (“ b”,“ e”) (“ c”,“ f”) ('a','g') (“ b”,“ h”) ('c','i') ('a','j') (“ b”,“ k”) ('c','l') ('d','g') ('e','h') ('f','i') ('d','j') ('e','k') ('f','l') (“ g”,“ j”) ('h','k') ('i','l')
我做错了什么?对不起,我的英语不好
答案 0 :(得分:1)
如何?
a = [['a','b','c'],['d','e','f'],['g','h','i'],['j','k','l']]
new_list = []
for i in range(len(a)): # Loop over the first subgroup
for j in range(i+1, len(a)): # Loop over the second subgroup
for k in range(len(a[0])): # Loop through the elements of each subgroup
new_list.append((a[i][k], a[j][k]))
new_list
[('a', 'd'), ('b', 'e'), ('c', 'f'),
('a', 'g'), ('b', 'h'), ('c', 'i'),
('a', 'j'), ('b', 'k'), ('c', 'l'),
('d', 'g'), ('e', 'h'), ('f', 'i'),
('d', 'j'), ('e', 'k'), ('f', 'l'),
('g', 'j'), ('h', 'k'), ('i', 'l')]
使用列表理解可以更简洁:
new_list = [(a[i][k], a[j][k]) for i in range(len(a))
for j in range(i+1, len(a))
for k in range(len(a[0])]
答案 1 :(得分:1)
使用itertools中的组合和一些numpy切片:
import numpy as np
import itertools
a = [['a','b','c'],['d','e','f'],['g','h','i'],['j','k','l']]
b = np.array(a)
m,n = b.shape
res = sorted([k for i in range(n) for k in itertools.combinations(b[:,i],2) ])
产量:
[('a','d'), ('a','g'), ('a','j'), ('b','e'), ('b','h'), ('b','k'), ('c','f'), ('c','i'), ('c','l'), ('d','g'), ('d','j'), ('e','h'), ('e','k'), ('f','i'), ('f','l'), ('g','j'), ('h','k'), ('i','l')]
答案 2 :(得分:0)
这正是zip
用于的用例:
from itertools import combinations
a = [['a','b','c'], ['d','e','f'], ['g','h','i'], ['j','k','l']]
result = [list(zip(*x)) for x in combinations(a, 2)]
# If you want to flatten the result:
flat_result = [item for row in result for item in row]
print(flat_result)
结果:
[[('a', 'd'), ('b', 'e'), ('c', 'f')],
[('a', 'g'), ('b', 'h'), ('c', 'i')],
[('a', 'j'), ('b', 'k'), ('c', 'l')],
[('d', 'g'), ('e', 'h'), ('f', 'i')],
[('d', 'j'), ('e', 'k'), ('f', 'l')],
[('g', 'j'), ('h', 'k'), ('i', 'l')]]
flat_result:
[('a', 'd'), ('b', 'e'), ('c', 'f'), ('a', 'g'), ('b', 'h'), ('c', 'i'), ('a', 'j'), ('b', 'k'), ('c', 'l'), ('d', 'g'), ('e', 'h'), ('f', 'i'), ('d', 'j'), ('e', 'k'), ('f', 'l'), ('g', 'j'), ('h', 'k'), ('i', 'l')]
或者如果您直接想要计算平面版本:
result = []
for x in combinations(a, 2):
result += list(zip(*x))