简体   繁体   中英

How to multiply two sublists within the same list?

I am new to python and SO. I want to multiply each element of lists in a list of lists to another list lying in the same list of lists and compare it with a reference value. This will be more clear with an example:

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

I want only those pairs whose product results in 10.

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

Edit: I prefer a method without any imports , since I am doing this for building logic and my editor doesn't contain any modules to import. Also, if there are more than 2 lists in a list of lists For eg. there are 3 Lists in a list of lists: then I want triplets for that sake. ANd if 4 lists then I need quadruples.

Here's my code attempt as requested.

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)

You can use itertools.product to find groups of numbers and filter them based on their 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]]
>>> 

In a comment you say you say you want code without any imports. Importing product from itertools and reduce do simplify and speed the code, but the job can be done without imports. Here is a recursive solution. I am not quite satisfied with this code but it seems to work and passes all my tests. I generalized the problem somewhat so that the input can have tuples or other sequences and not just lists.

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))

The printout from that code is

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

I'll leave it to you to remove what you consider to be duplicates. I can think of situations where you would want this full list, however.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM