您好我正在使用python。我正在处理一个数字列表
A = [7,9,6,8]
我希望得到顺序排列的数字排列。期望的输出如下:
[(6), (7), (8), (9), (6, 7), (7, 8), (8, 9), (6, 7, 8), (7, 8, 9)]
我的代码如下:
>>> import itertools
>>> A = [6,8,7,9]
>>> def comb(myc: list):
retcol = []
for i in range(1,len(myc)):
retcol += list(itertools.combinations(myc,i))
return retcol
>>> S = sorted(A, key=int)
>>> comb(S)
[(6,), (7,), (8,), (9,), (6, 7), (6, 8), (6, 9), (7, 8), (7, 9), (8, 9), (6, 7, 8), (6, 7, 9), (6, 8, 9), (7, 8, 9)]
>>>
[(6,), (7,), (8,), (9,), (6, 7), (6, 8), (6, 9), (7, 8), (7, 9), (8, 9), (6, 7, 8), (6, 7, 9), (6, 8, 9), (7, 8, 9)]
我有两个问题:
for loop
,是否有更好的方法来获得这样的结果?也许是list comprehension
答案 0 :(得分:3)
怎么样
l = sorted(A)
[l[j : j + i] for i in range(1, len(l)) for j in range(len(l) - i + 1)]
这会产生
[[6], [7], [8], [9], [6, 7], [7, 8], [8, 9], [6, 7, 8], [7, 8, 9]]
这不是你要求的,但我猜你刚犯错(例如,让第一个元素是一个裸数而不是一元素元组或单元素列表)