1. Nested list format
The nested list alis simulated in this article is as follows:
alis = [['xx', 'yy'], [2], ['Four', 4], ['99']]
Nested list alis has the following characteristics:
1. Nested list alis, with only two layers, and the format is: [[]].
2. All elements in the first level list are list types.
2. Nested list expansion method
(I) for loop
The easiest thing to think of is to use a for loop to expand.
Using the for loop and combining some processing methods of the list itself, there are many ways to write it.
The three common writing methods are as follows:
(1) for loop + append()
alis = [['xx', 'yy'], [2], ['Four', 4], ['99']] blis = [] for lis in alis: if type(lis) == list: for i in lis: (i) else: (lis) print('alis after expanding:', blis)
After the alis is expanded: ['xx', 'yy', 2, 'four', 4, '99']
(2) For loop + python self-add
Principle: The for loop is equivalent to turning a nested list into a single-layer list, and adding it is equivalent to adding a single-layer list.
alis = [['xx', 'yy'], [2], ['Four', 4], ['99']] blis = [] for lis in alis: blis += lis print("Alis expands:", blis)
After the alis is expanded: [‘xx’, ‘yy’, 2, ‘four’, 4, ‘99’]
(3) for loop + extend()
alis = [['xx', 'yy'], [2], ['Four', 4], ['99']] blis = [] for lis in alis: (lis) print("Alis expands:", blis)
After the alis is expanded: [‘xx’, ‘yy’, 2, ‘four’, 4, ‘99’]
(II) List comprehension
List comprehension, a simple version of for loop
alis = [['xx', 'yy'], [2], ['Four', 4], ['99']] blis = [i for k in alis for i in k] print("Alis expands:", blis)
After the alis is expanded: [‘xx’, ‘yy’, 2, ‘four’, 4, ‘99’]
(III) Use the sum function
How to use: sum(necked list,[])
alis = [['xx', 'yy'], [2], ['Four', 4], ['99']] blis = sum(alis, []) print("Alis expands:", blis)
After the alis is expanded: [‘xx’, ‘yy’, 2, ‘four’, 4, ‘99’]
The above method of expanding nested lists is mainly aimed at the situation where two layers of nested lists and the second layer is a list. For more related python to expand nested list content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!