I'm newbie, and I have two lists and want to combine them into a tuple, by random all possible element, without using any packet such as itertools packet. Like this example:
list1 = ["a", "b", "c"]
list2 = ["wow", 2]
and the output:
>>> new_tuple = (["a","wow"],["b","wow"],["c","wow"],["a",2],["b",2],["c",2])
Could you help me? Thank you in advance
CodePudding user response:
You could make use of itertools
to make the permutation you request like the following should work for you:
import itertools
list1 = ["a", "b", "c"]
list2 = ["wow", 2]
all_combinations = []
list1_permutations = itertools.permutations(list1, len(list2))
for each_permutation in list1_permutations:
zipped = zip(each_permutation, list2)
all_combinations.append(list(zipped))
print(all_combinations)
Output looks like following:
[[('a', 'wow'), ('b', 2)], [('a', 'wow'), ('c', 2)], [('b', 'wow'), ('a', 2)], [('b', 'wow'), ('c', 2)], [('c', 'wow'), ('a', 2)], [('c', 'wow'), ('b', 2)]]```
CodePudding user response:
Python3 one-liner using list comprehension
list1 = ['a', 'b', 'c']
list2 = ['wow', 2]
new_tuple = [[l1, l2] for l2 in list2 for l1 in list1]
print(new_tuple)
# [['a', 'wow'], ['b', 'wow'], ['c', 'wow'], ['a', 2], ['b', 2], ['c', 2]]
CodePudding user response:
Use itertools.product
:
from itertools import product
new_tuple = tuple([a, b] for b, a in product(list2, list1))
# (['a', 'wow'], ['b', 'wow'], ['c', 'wow'], ['a', 2], ['b', 2], ['c', 2])
CodePudding user response:
import random
list1 = ["a", "b", "c"]
list2 = ["wow", 2]
new_tuple = ()
for x in (len(list1) len(list2)):
randInt = random.randint(0, len(list1))
randInt2 = random.randint(0, len(list2))
new_tuple = [list1[randInt], list2[randInt2]]
This is really simple python. Try the code out.
CodePudding user response:
What you want is basically a cartesian product. Try a list comprehension with itertools, such as:
import itertools
list1 = ["a", "b", "c"]
list2 = ["wow", 2]
new_tuple = [x for x in itertools.product(list1, list2)]
CodePudding user response:
For converting 2 list to tuple, there is method .zip:
list(zip(list1, list2))
but it's only add elements in your case: (["a", "wow"], ["b", "2"]], so:
a = ("John", "Charles", "Mike")
b = ("Jenny", "Christy", "Monica")
tuples = []
def combineTuples(listA, listB):
for i in range(len(listA)):
for j in range(len(listB)):
tuples.append((a[i], b[j]))
x = combineTuples(a, b)
print(tuples)
output: [('John', 'Jenny'), ('John', 'Christy'), ('John', 'Monica'), ('Charles', 'Jenny'), ('Charles', 'Christy'), ('Charles', 'Monica'), ('Mike', 'Jenny'), ('Mike', 'Christy'), ('Mike', 'Monica')]
output with your data is idnetical, but without order.
[('a', 'wow'), ('a', 2), ('b', 'wow'), ('b', 2), ('c', 'wow'), ('c', 2)]
CodePudding user response:
You can use itertools
import itertools
list1 = ["a", "b", "c"]
list2 = ["wow", 2]
c = tuple(itertools.product(list1, list2))
print(c)