我是新手,我有两个列表,并希望将它们组合成一个元组,随机所有可能的元素,而不使用任何数据包,如itertools数据包.就像这个例子:
list1 = ["a", "b", "c"]
list2 = ["wow", 2]
和输出:
>>> new_tuple = (["a","wow"],["b","wow"],["c","wow"],["a",2],["b",2],["c",2])
你能帮我吗?提前谢谢你
Python3使用列表生成器的一行代码
list1 = ['a', 'b', 'c']
list2 = ['wow', 2]
new_tuple = 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])
您可以使用itertools
import itertools
list1 = ["a", "b", "c"]
list2 = ["wow", 2]
c = tuple(itertools.product(list1, list2))
print(c)
您可以使用itertools
来进行您请求的排列,如下所示:
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)
输出如下:
[[('a', 'wow'), ('b', 2)], [('a', 'wow'), ('c', 2)], [('b', 'wow'), ('a', 2)], [('b', 'wow'), ('c', 2)], [('c', 'wow'), ('a', 2)], [('c', 'wow'), ('b', 2)]]```
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]]
这是一个非常简单的python。试代码。
你想要的基本上是一个笛卡尔积。尝试使用itertools进行列表推导,例如:
import itertools
list1 = ["a", "b", "c"]
list2 = ["wow", 2]
new_tuple = [x for x in itertools.product(list1, list2)]
使用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])
要将2个列表转换为元组,有.zip方法:
list(zip(list1, list2))
但是它只是在你的情况下添加元素:(["a", "哇"], ["b", "2"]],所以:
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)
输出:(("约翰","珍妮")("约翰","小茉莉")("约翰","莫尼卡")("查尔斯"、"珍妮")("查尔斯"、"小茉莉")("查尔斯"、"莫尼卡")("迈克","珍妮")("迈克","小茉莉")("迈克","莫尼卡")]
输出与您的数据相同,但没有顺序。
[(' a ', '哇'),(' a ', 2),(‘b’,‘哇’),(' b ', 2), (' c ', '哇'),(' c ', 2)]