【发布时间】:2018-11-10 08:15:39
【问题描述】:
我正在尝试随机匹配列表和元组中的两个元素。我的目标是创建一个具有 1 对 1 匹配的字符串。
下面是我最终想要实现的理想代码。
>>> color = ['red', 'orange', 'yellow']
>>> transportation = ('car', 'train', 'airplane')
>>> combination(color, transportation)
['a red car', 'a yellow train', 'a orange airplane']
这是我目前所拥有的。
def combination(color, transportation):
import random
import itertools
n = len(colors)
new = random.sample(set(itertools.product(color, transportation)), n)
return new
[('red', 'car'), ('orange', 'car'), ('red', 'airplane')]
如您所见,颜色“红色”被使用了两次,交通工具“汽车”也被使用了两次。
我无法将每种交通工具仅分配给一种颜色,而将每种颜色仅分配给一种交通工具。
另外,我非常感谢有关如何将元组转换为字符串的任何提示。 ex) ('red', 'car') -> 'a red car' 对于我在列表中的每个项目。
【问题讨论】:
-
查看 random.shuffle() 方法(“传输必须是列表)。
-
'a orange airplane'你确定它真的很理想吗?
标签: python python-3.x list data-structures