如何将同一列表中的两个子列表相乘?

时间:2018-07-21 19:50:56

标签: python list

我是python和SO的新手。我想将列表列表中的每个列表元素与位于相同列表列表中的另一个列表相乘,并将其与参考值进行比较。通过一个示例将更加清楚:

for L = [[1,2,3,4,5,10],[3,2,4,1,5,10]] ##there can be more than 2 lists in this list of lists

我只想要乘积结果为10的那对。

Out: L = [[1,10],[2,5]]

编辑:我更喜欢没有任何导入的方法,因为我这样做是为了构建逻辑,并且我的编辑器不包含任何要导入的模块。另外,如果列表列表中有两个以上的列表,例如。列表列表中有3个列表:那么我想要三胞胎。如果有4个列表,那么我需要四倍。

这是我要求的代码尝试。

N = []
J = []
F = []
Z = []
S = []
O = []
num = input("Enter no. of elements in list")
print ('Enter numbers')
prod = 1
for i in range(int(num)):
    n = input("num :")
    N.append(int(n))
for x in N:
    prod = prod*x
print (prod)
k = int(input("Enter no. of splits:"))
##d = [[] for x in xrange(k)]
##var_dict = [] 
for o in range(1,prod+1):
    if prod%o == 0:
        J.append(o)
print (J)
for g in range(k): 
  O.append(J*(k-1))
print (O)
for a in range(len(O)):
    for b in range(len(O)):
        if O[i]*O[i+1] == prod:
            Z.extend(O)

##Z = [[a, b] for a in J for b in F if a*b == prod] ##imp
print (Z)
for e in Z:
    if e not in S and sorted(e) not in S:
        S.append(e)
print (S)

2 个答案:

答案 0 :(得分:2)

您可以使用itertools.product查找数字组并根据其乘积进行过滤

>>> from itertools import product
>>> from functools import reduce
>>> lst = [[1,2,3,4,5,10],[3,2,4,1,5,10]]
>>> ans = [p for p in product(*lst) if reduce(lambda x,y:x*y, p) == 10]
>>> # Remove duplicates
>>> ans = list(map(list, set(map(frozenset, ans))))
>>> print (ans)
[[1, 10], [2, 5]]
>>> 

答案 1 :(得分:1)

在一条评论中,您说您想要不带任何导入的代码。从itertools和product导入reduce确实可以简化和加速代码,但是无需导入即可完成此工作。这是一个递归解决方案。我对这段代码不太满意,但是它似乎可以正常工作并通过了我的所有测试。我对此问题进行了概括,以便输入可以具有元组或其他序列,而不仅仅是列表。

def prod_is_target(seq_of_seqs, target):
    """Return a list of lists, where each sublist contains one member
    of each input subsequence in order, and the product of those
    members equals the target value. If there is no such list possible,
    return None. If seq_of_seqs is empty, return an empty list if the
    target is 1 and return None otherwise.
    """
    if not seq_of_seqs:  # if is empty sequence
        return [] if target == 1 else None
    result = []
    for val in seq_of_seqs[0]:
        if target % val:  # skip if target is not a multiple of val
            continue
        prodlists = prod_is_target(seq_of_seqs[1:], target // val)
        if prodlists is None: # skip if failed with later sublists
            continue
        if not prodlists:  # if is empty list
            result.append([val])
        else:
            for prodlist in prodlists:
                result.append([val] + prodlist)
    return result if result else None

print(prod_is_target([[1,2,3,4,5,10], [3,2,4,1,5,10]], 10))

该代码的打印输出为

[[1, 10], [2, 5], [5, 2], [10, 1]]

我将留给您删除您认为重复的内容。不过,我可以想到您想要完整列表的情况。