Python 如何从嵌套列表中提取元素
我有一个嵌套列表,格式为Python 如何从嵌套列表中提取元素,python,Python,我有一个嵌套列表,格式为[[1,2,3],[3,4,5],[8,6,2,5,6],[7,2,9] 我想将第一个项目提取到新列表中,第二个项目提取到新列表中,其余项目提取到新嵌套列表中: a = [1,3,8,7] b = [2,4,6,2], c = [[3], [5], [2,5,6],[9]] 是否可以避免使用for循环,因为真正的嵌套列表相当大?如果有任何帮助,我将不胜感激。目前,我无法想出没有for循环的解决方案,我希望以后能够更新我的答案 下面是一个使用for循环的解决方案: dat
[[1,2,3],[3,4,5],[8,6,2,5,6],[7,2,9]
我想将第一个项目提取到新列表中,第二个项目提取到新列表中,其余项目提取到新嵌套列表中:
a = [1,3,8,7] b = [2,4,6,2], c = [[3], [5], [2,5,6],[9]]
是否可以避免使用for循环,因为真正的嵌套列表相当大?如果有任何帮助,我将不胜感激。目前,我无法想出没有for循环的解决方案,我希望以后能够更新我的答案 下面是一个使用for循环的解决方案:
data = [[1,2,3], [3,4,5], [8,6,2,5,6], [7,2,9]]
list1 = []
list2 = []
list3 = []
for item in data:
else_list = []
for index, value in enumerate(item):
if index == 0:
list1.append(value)
elif index == 1:
list2.append(value)
else:
else_list.append(value)
list3.append(else_list)
print(list1)
print(list2)
print(list3)
输出
[1, 3, 8, 7]
[2, 4, 6, 2]
[[3], [5], [2, 5, 6], [9]]
solution_1 performance:
9.580000000000005e-05
solution_2 performance:
1.7200000000001936e-05
solution_3 performance:
1.7499999999996685e-05
为了好玩,我还与大家分享了一个性能比较,在使用一个for loop Meysam时做得很好
import timeit
# a = [1,3,8,7] b = [2,4,6,2], c = [[3], [5], [2,5,6],[9]]
def solution_1():
data = [[1, 2, 3], [3, 4, 5], [8, 6, 2, 5, 6], [7, 2, 9]]
list1 = []
list2 = []
list3 = []
for item in data:
else_list = []
for index, value in enumerate(item):
if index == 0:
list1.append(value)
elif index == 1:
list2.append(value)
else:
else_list.append(value)
list3.append(else_list)
def solution_2():
arr = [[1, 2, 3], [3, 4, 5], [8, 6, 2, 5, 6], [7, 2, 9]]
first_arr, second_arr, third_arr = [], [], []
for nested in arr:
first_arr.append(nested[0])
second_arr.append(nested[1])
third_arr.append(nested[2:])
def solution_3():
l = [[1, 2, 3], [3, 4, 5], [8, 6, 2, 5, 6], [7, 2, 9]]
a = [i[0] for i in l]
b = [i[1] for i in l]
c = [i[2:] for i in l]
if __name__ == "__main__":
print("solution_1 performance:")
print(timeit.timeit("solution_1()", "from __main__ import solution_1", number=10))
print("solution_2 performance:")
print(timeit.timeit("solution_2()", "from __main__ import solution_2", number=10))
print("solution_3 performance:")
print(timeit.timeit("solution_3()", "from __main__ import solution_3", number=10))
输出
[1, 3, 8, 7]
[2, 4, 6, 2]
[[3], [5], [2, 5, 6], [9]]
solution_1 performance:
9.580000000000005e-05
solution_2 performance:
1.7200000000001936e-05
solution_3 performance:
1.7499999999996685e-05
最终,无论你的解决方案是什么,你都必须在你的代码中有一个
for
循环,我的建议是尽可能使它干净易读
话虽如此,以下是我的建议:
arr = [[1,2,3], [3,4,5], [8,6,2,5,6], [7,2,9]]
first_arr, second_arr, third_arr = [], [], []
for nested in arr:
first_arr.append(nested[0])
second_arr.append(nested[1])
third_arr.append(nested[2:])
这是一个使用列表理解的简单、简单的循环解决方案,但看看它是否足够快
l=[[1,2,3],[3,4,5],[8,6,2,5,6],[7,2,9]]
a=[i[0]表示l中的i]
b=[i[1]表示l中的i]
c=[i[2:]表示l中的i]
返回:
>a
[1, 3, 8, 7]
>>b
[2, 4, 6, 2]
>>c
[[3], [5], [2, 5, 6], [9]]