【问题标题】:merging two elements from two list in random随机合并两个列表中的两个元素
【发布时间】: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


【解决方案1】:

类似的东西可能会起作用:

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

【讨论】:

    【解决方案2】:

    你也可以这样试试。

    使用random.shuffle()zip()

    >>> import random
    >>>
    >>> color = ['red', 'orange', 'yellow']
    >>> transportation = ('car', 'train', 'airplane')
    >>>
    >>> random.shuffle(color)
    >>>
    >>> list(zip(color, transportation))
    [('yellow', 'car'), ('orange', 'train'), ('red', 'airplane')]
    >>>
    >>> random.shuffle(color)
    >>> list(zip(color, transportation))
    [('red', 'car'), ('yellow', 'train'), ('orange', 'airplane')]
    >>>
    >>> random.shuffle(color)
    >>> list(zip(color, transportation))
    [('orange', 'car'), ('red', 'train'), ('yellow', 'airplane')]
    >>>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      • 2019-04-26
      • 1970-01-01
      • 2019-04-28
      • 2019-04-27
      • 2016-08-14
      • 1970-01-01
      相关资源
      最近更新 更多