我试图从列表和元组中随机匹配两个元素。我的目标是创建一个 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' 对于我在列表中的每个项目。
这样的事情可能会奏效:
from random import shuffle
color = ['red', 'orange', 'yellow']
transportation = ('car', 'train', 'airplane')
t_list = list(transportation)
shuffle(color)
shuffle(t_list)
new_lst = list(zip(color, t_list))
print(new_lst)
# [('red', 'train'), ('orange', 'car'), ('yellow', 'airplane')]
请注意,您必须转换transportation
为random.shuffle
工作列表:shuffle
就地修改列表。
至于你问题的第二部分:str.join
将帮助:
for col_trans in new_lst:
print(' '.join(col_trans))
# red train
# orange car
# yellow airplane
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句