2024-10-02 12:27:49 发布
网友
我有一个变量如下:
symbols = ['KEL','BYCO']
我想要一个函数,将这些符号的组合作为输出,如下所示
['KEL'],['BYCO'] and ['KEL','BYCO']
如果一个变量中包含n个字符串,有没有人能推荐一个库/函数来实现这样的组合呢。你知道吗
我想这就是你想要的:
Python 2.7.6 (default, Oct 26 2016, 20:30:19) [GCC 4.8.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> from itertools import combinations, chain >>> >>> def powerset(iterable): ... "powerset([1,2,3]) > () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" ... s = list(iterable) ... return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) ... >>> symbols = ['KEL','BYCO'] >>> >>> list(powerset(symbols)) [(), ('KEL',), ('BYCO',), ('KEL', 'BYCO')]
这里的powerset函数直接从文档中提取:https://docs.python.org/2/library/itertools.html
powerset
我想这就是你想要的:
这里的
powerset
函数直接从文档中提取:https://docs.python.org/2/library/itertools.html相关问题 更多 >
编程相关推荐