In some cases, we need to do something about the list, such as multiplying each element in the list by 2, which is generally the traversal of each element multiplied by 2. Then it will be two lines to write it down. And this will modify the original list, if you want to not modify the original list, there are more than one line.
1 mylist = [1,3,5,7]2 copylist = []3 for in mylist: 4 copylist.append (i * 2)5print(copylist)
One look is a bloated word.
Python provides a more straightforward way to do this:
1 mylist = [1,3,5,7]2 for in MyList]3print (mylist) 4 Print (copylist)
Output:
1 3 5 7
2 6 10 14
It's much easier to write like this. And it's easy to understand, first of all, for Elem in MyList this part is a loop--declaring elem temporary variable, traversing mylist list. The elem*2, however, indicates that the Elem temporary variable is multiplied by 2, and the last [] is well understood, because what we need is a list. The whole thing is to take the element from the MyList list, and return a list of each element multiplied by 2.
The power of the list explanation is not just that, it can also be conditional filtering:
1 mylist = [1,2,3,4,5,6,7,8,9,10]2forif elem% 2 = = 0] 3print(copylist)
Then this will output all the even two of the list.
In general, the list is interpreted with LINQ like in C #.
Python Learning -35.python list comprehensions (List explanation | list generation)