Python - 查找所有嵌套列表的起始索引
在本文中给出一个矩阵,任务是编写一个Python程序来计算所有嵌套列表的起始索引。
例子:
Input : test_list = [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]]
Output : [0, 1, 5, 7, 13]
Explanation : 1 + 4 = lengths of 2 initial lists = 5, 3, of 3rd list start from 5th index [ 0 based indexing ],
hence 5. as 3rd element in result list.
Input : test_list = [[5], [9, 3, 1, 4], [3, 2], [3, 4, 5]]
Output : [0, 1, 5, 7]
Explanation : 1 + 4 = lengths of 2 initial lists = 5, 3, of 3rd list start from 5th index [ 0 based indexing ],
hence 5. as 3rd element in result list.
方法 #1:使用循环 + len()
在这种情况下,每个子列表的长度使用 len() 计算并求和,累积,并作为中间结果添加。初始索引是子列表长度的导数。
Python3
# Python3 code to demonstrate working of
# Initial element index in Matrix
# Using loop
# initializing list
test_list = [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]]
# printing original list
print("The original list is : " + str(test_list))
res = []
lens = 0
for sub in test_list:
# lengths of sublist computed
res.append(lens)
lens += len(sub)
# printing result
print("Initial element indices : " + str(res))
Python3
# Python3 code to demonstrate working of
# Initial element index in Matrix
# Using accumulate() + map() + len()
from itertools import accumulate
# initializing list
test_list = [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]]
# printing original list
print("The original list is : " + str(test_list))
# ignoring last index using "-1"
# sum starting at 0
res = [0, *accumulate(map(len, test_list[:-1]))]
# printing result
print("Initial element indices : " + str(res))
Python3
# This will print all the starting indexes
# of sublists inside this list
lis = [[1,2,3],4,5,[6,7,8],9,0,[10]]
for i in lis:
if type(i) == list:
print(lis.index(i), end=",")
# This code is contributed by BABAji
输出:
The original list is : [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]]
Initial element indices : [0, 1, 5, 7, 13]
方法#2:使用accumulate() + map() + len()
在这里,我们使用accumulate() 执行求和任务,map() 用于获得使用len() 计算的所有子列表的长度。
蟒蛇3
# Python3 code to demonstrate working of
# Initial element index in Matrix
# Using accumulate() + map() + len()
from itertools import accumulate
# initializing list
test_list = [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]]
# printing original list
print("The original list is : " + str(test_list))
# ignoring last index using "-1"
# sum starting at 0
res = [0, *accumulate(map(len, test_list[:-1]))]
# printing result
print("Initial element indices : " + str(res))
输出:
The original list is : [[5], [9, 3, 1, 4], [3, 2], [4, 7, 8, 3, 1, 2], [3, 4, 5]]
Initial element indices : [0, 1, 5, 7, 13]
方法 #3:使用 type() 和循环以及 if 语句
在这里,我们只需检查列表中元素的类型,如果它是另一个列表,我们将打印其索引,否则不会。无论列表中非列表类型元素的数量如何,此方法都将起作用
蟒蛇3
# This will print all the starting indexes
# of sublists inside this list
lis = [[1,2,3],4,5,[6,7,8],9,0,[10]]
for i in lis:
if type(i) == list:
print(lis.index(i), end=",")
# This code is contributed by BABAji
输出:
0,3,6,