我正在练习Python编程,现在我希望看到一种优雅的方法来执行以下操作:我有一个包含以下形式的86行(一行是4个元素的列表)的列表:
[[1, 2, 15, 16], [1, 3, 14, 16], ..., [6, 8, 9, 11], [7, 8, 9, 10]]
然后我怎样才能找到所有四个4元素行的列表,这样我就可以置换单行的元素并按行分组添加它们[34 34 34 34]?
例如,如果我采取行
[1,2,15,16], [6,7,10,11], [3,8,9,14], [4,5,12,13]
我可以将它们加到[34 34 34 34]如下:1 + 6 + 14 + 13 = 2 + 11 + 9 + 12 = 15 + 7 + 8 + 4 = 16 + 10 + 3 + 5。
我希望输出是二维表
[[1,2,15,16], [6,7,10,11], [3,8,9,14], [4,5,12,13]]
其中例如A [0] = [1,2,15,16]和A [0] [0] = 1。如果我不能将四个总和的组合形成为34,那么它将不输出任何内容。
我试过的是
for a,b,c in itertools.product(range(0,len(row_set)), range(0,len(row_set)),range(0,len(row_set))):
print(row_set[a],row_set[b],row_set[c])
但我不确定如何保证我可以对列表进行置换,以便添加组件总是34。
答案 0 :(得分:1)
我没有测试过这么多,但它应该接近你想要的,毫无疑问它可以被优化,这是在四个子列表的列表中进行测试。
from itertools import product, izip
l = [[1,2,15,16], [6,7,10,11], [3,8,9,14], [4,5,12,13]]
prod = list(product(*l)) # get all possible products of the elements
def grouper(iterable, n):
args = [iter(iterable)] * n
return izip(*args)
# 4 choices for each list so 4*4*4*4= 256
groups = grouper(prod,len(prod)/ 4) # group prod in 4 equal groups(len of each sub list)
count = 0
flatten_check = [] # keep list of elements of all products that equal 34
for comb in groups:
# check if any product is equal to 34 in groups
check = [c for c in comb if sum(c) == 34]
flatten_check += [y for x in check for y in x]
if check:
count += 1 # if at least one of the products for each comb equals 34 add 1 to counter
flatten_l = [ x for y in l for x in y] # flatten original list to compare elements
# if each comb had a product that equaled 34, count should equal 4
# if we used all elements in l we satisfied our requirement
if count == 4 and all(item in flatten_check for item in flatten_l):
print l # print original list
对于python 3:
from itertools import product
prod = list(product(*l)) # get all possible products of the elements
def grouper(n, iterable):
args = [iter(iterable)] * n
return zip(*args) # izip is gone in python3 as zip now returns an iterator instead of a list
groups = grouper(len(prod)// 4,prod) # group prod in 4 equal groups(len of each sub list)
count = 0
flatten_y = [] # keep list of elements of all products that equal 34
for comb in groups:
# check if any product is equal to 34 in groups
check = [c for c in comb if sum(c) == 34]
flatten_y += [y for x in check for y in x]
if check:
count += 1 # if at least one of the products for each comb equals 34 add 1 to counter
flatten_l = [ x for y in l for x in y] # flatten original list to compare elements
# if each comb had a product that equaled 34 count should equal 4
# if we used all elements in l we satisfied our requirement
if count == 4 and all(item in flatten_y for item in flatten_l):
print (l) # print original list as we have met