随机合并两个列表中的两个元素

时间:2018-11-10 08:15:39

标签: python python-3.x list data-structures

我试图随机匹配list和tuple中的两个元素。我的目标是创建一个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')]

如您所见,颜色“红色”被使用两次,运输“汽车”也被使用两次。

我在将每种运输方式仅分配给一种颜色并将每种颜色分配给其中一种运输时遇到了麻烦。

此外,我非常感谢有关如何将元组变成字符串的任何提示。 例如)('red','car')->'a a red car'for this list。

2 个答案:

答案 0 :(得分:1)

类似的方法可能起作用:

a

请注意,您必须将#include <iostream> #include <memory> void testfunc(std::unique_ptr<int>& x) { auto& b(x); // 'b' is an alias of 'x' and 'x' is an alias of 'a' b = std::make_unique<int>(6); // Setting 'b' to 6 meaning setting 'a' to 6... /* Now you can't do 'x = b' since you cannot assign a value to an alias and it is like a 'circular assignment operation'...*/ } int main() { std::unique_ptr<int> a(new int(5)); std::cout << *a << std::endl; // 5 : Nothing happens, just initialization... testfunc(a); // It does not affect the reference... std::cout << *a << std::endl; /* 6 : Since reference is an 'alias', you changed 'a' as well...*/ } // It is freed after use by the destructor... 转换为random.shuffle工作的列表: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')] 就地修改列表。

对于您问题的第二部分:str.join将有所帮助:

transportation

答案 1 :(得分:0)

您也可以这样尝试。

  

使用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')]
>>>