0

I have this code here:

import itertools

col_groups = [c1+c2 for c1, c2 in itertools.product(d1_columns, d2_columns)]

How can I do something like this without itertools? a non-pythonic way of doing it.

2
  • Why would you want to do that? Commented Nov 27, 2013 at 18:49
  • @PeterDeGlopper just curiosity. Commented Nov 27, 2013 at 19:13

3 Answers 3

3

Perhaps with a nested list comprehension if you just need the cartesian product of two lists.

[ i + j for i in d1_columns for j in d2_columns ]
Sign up to request clarification or add additional context in comments.

Comments

1

You can always use the code given in itertools.product

def product(*args, **kwds):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

7 Comments

humm thats in interesting way of avoiding to use itertools.
I am getting this error tho: unsupported operand type(s) for *: 'map' and 'int'
What are the parameters you are passing?
I have it something like this: I created above function... then I do a function call and pass the function like this inside another function: col_groups = [c1+c2 for c1, c2 in product(d1_columns, d2_columns)]
Can you please show me what are dl_columns and d2_columns?
|
1
def colGroups(d1, d2):
  answer = []
  for c1 in d1:
    for c2 in d2:
      answer.append(c1+c2)
  return answer

Testing:

>>> d1 = list(range(10))
>>> d2 = list(range(10,20))
>>> d1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> d2
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> def colGroups(d1, d2):
...   answer = []
...   for c1 in d1:
...     for c2 in d2:
...       answer.append(c1+c2)
...   return answer
... 
>>> colGroups(d1, d2)
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28]

... or the nested listcomp equivalent:

colGroups = [c1+c2 for c1 in d1 for c2 in d2]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.