在Python中打印列表的所有子列表
给定一个列表,打印一个列表的所有子列表。
例子:
Input : list = [1, 2, 3]
Output : [[], [1], [1, 2], [1, 2, 3], [2],
[2, 3], [3]]
Input : [1, 2, 3, 4]
Output : [[], [1], [1, 2], [1, 2, 3], [1, 2, 3, 4],
[2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]
方法:
该方法将运行两个嵌套循环,直到给定列表的长度。外循环 i 从 0 遍历到列表的长度,内循环从 0 遍历到 i。需要将长度加 1,因为范围仅从 0 到 i-1。要获取子数组,我们可以使用切片来获取子数组。
Step 1: Run a loop till length+1 of the given list.
Step 2: Run another loop from 0 to i.
Step 3: Slice the subarray from j to i.
Step 4: Append it to a another list to store it
Step 5: Print it at the end
以下是上述方法的Python实现:
Python
# Python program to print all
# sublist from a given list
# function to generate all the sub lists
def sub_lists (l):
lists = [[]]
for i in range(len(l) + 1):
for j in range(i):
lists.append(l[j: i])
return lists
# driver code
l1 = [1, 2, 3]
print(sub_lists(l1))
输出:
[[], [1], [2], [1, 2], [3], [2, 3], [1, 2, 3]]