请教各位大侠一个 排列组合的问题,非常感谢!

2016-08-30 18:28:14 +08:00
 lostapple
  1. a 是一个列表,其元素是列表, 例: a = [[2,3], [3,4,5,6], [9], [88,77]]
  2. a 列表的长度不确定
  3. a 列表中的元素也是长度不确定的列表

取 a 列表中的 num 个元素(也是列表),每个元素中取一个字符,与其他元素中的字符进行排列组合

向各位大侠请教,怎样设计代码才更 pythonic? 有没有更好的处理方法?

thanks for yr time !

'''

# using python3.5

import itertools
import copy

# 对两个列表中元素进行排列
def listmlist(list1, list2):
    for a in list1:
        for b in list2:
            yield str(a) + str(b)
        	yield str(b) + str(a)

# 取列表中所有的元素进行排列,采用递归
def alllist(u):
    for i in u:
        temp = copy.deepcopy(u)
        temp.remove(i)
        if len(temp) > 1:
            return set(listmlist(i, alllist(temp)))
        else:
            return set(listmlist(i, temp[0]))

# 取列表中 num 个元素进行排列
def permute(u, num):
    result = set()
	# 取 2 个元素的情况
    if num == 2:
        for g in itertools.combinations(u, r=num):
            result.update(set(listmlist(*g)))
        return result
	# 取 1 个元素的情况
    if num == 1:
        for g in itertools.combinations(u, r=num):
            result.update(set(g[0]))
        return result

	# 取所有元素的情况,调用 alllist()
    if len(u) == num:
        return alllist(u)  

	# 取两个元素以上的情况
    for i in u:
        temp = copy.deepcopy(u)
        temp.remove(i)

        for g in itertools.combinations(temp, r=num-1):
            if len(g) > 2:
                result.update(makepasswd(list(g), num=len(g)))   #这个地方总觉得有问题,算是递归吗?
            else:
                result.update(set(listmlist(i, listmlist(*g))))
    return result

if __name__ == '__main__':
	a =	[[2,3], [3,4,5,6], [9], [88,77]]
	print(permute(a, 2))
	print(permute(a, 4))
	print(permute(a, 1))

'''

1444 次点击
所在节点    Python
2 条回复
hitmanx
2016-08-30 18:49:21 +08:00
output = [s for s in itertools.product(*a)]

花了 2 分钟,拿 google 一搜就有了"python nested lists permutation"..
lostapple
2016-08-31 09:07:52 +08:00
@hitmanx 谢谢,没注意 product 方法,现成的方法确实方便啊,继续努力

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/302738

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX