Permutation of two lists
本问题已经有最佳答案,请猛点这里访问。
我有两个列表:
1 2  | first = ["one","two","three"] second = ["five","six","seven"]  | 
我希望这两个列表的每一个组合,但是第一个列表中的元素总是在前面。我试过这样的方法:
1 2 3  | for i in range(0, len(combined) + 1): for subset in itertools.permutations(combined, i): print('/'.join(subset))  | 
号
其中"组合"是这两个列表的组合,但这给了我所有的可能性,我只想让第一个列表中的元素位于第一位。例如:
1  | ["onefive","twosix","twofive"]  | 
等。有人知道我怎么做这个吗?
有时使用普通循环是最简单的:
1 2 3 4  | ["{}/{}".format(j,k) for j in first for k in second] >>> ['one/five', 'one/six', 'one/seven', 'two/five', 'two/six', 'two/seven', 'three/five', 'three/six', 'three/seven']  | 
这应该可以满足您的需求:
1 2 3  | >>> ["/".join(x) for x in itertools.product(first, second)] ['one/five', 'one/six', 'one/seven', 'two/five', 'two/six', 'two/seven', 'three/five', 'three/six', 'three/seven'] >>>  | 
您也可以在不使用
1 2 3  | >>> [x +"/" + y for x in first for y in second] ['one/five', 'one/six', 'one/seven', 'two/five', 'two/six', 'two/seven', 'three/five', 'three/six', 'three/seven'] >>>  | 
号