Basic Python Learning (vi)

Source: Internet
Author: User

List understanding

A common application is to make a new list where each element is the result of a number of actions that are applied to each member or iteration of another sequence, or create a new list that satisfies the criteria for those elements:

 #List comprehensions 

"" "Common applications is to make new lists where each element is the result of some ope Rations applied to
each member of another sequence or iterable, or to create a subsequence of those elements the
SA Tisfy a certain condition. "" "

Squares = []
for x in range:
Squares.append (x**2)

Print (squares)
Print (x)
"" Note That this creates (or overwrites) a variable named X that still exists after the loop completes.
We can calculate the list of squares without any side effects using: "" "
Squares1 = List (map (lambda y:y**2, range (1 0))
Print (squares1)
#print (y) err:y is not defined

Squares3 = [z** 2 for z in range
Print (SQUARES3)
#print (z) err:z are not defined

run Result:

D:\Python3.6.1\python.exe f:/python_workspace/tutorial/lists3.py
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
9
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Process finished with exit code 0

A list expression containing [] can pass through a for statement through 0 or more for or if statements.

Then zero or more for or if clauses. """
RESULT1 = [(x, Y) for x in [All-in-A-z] for y in [3,1,4] if x! = y]
Print (RESULT1)
i = j = 0
while (I < 7):
Print ("-------------------")
while (J < 2):
Print (Result1[i][j])
j = j + 1
j = 0
i = i +1
Continue

Operation Result:

[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
-------------------
1
3
-------------------
1
4
-------------------
2
3
-------------------
2
1
-------------------
2
4
-------------------
3
1
-------------------
3
4


Study reference: Https://docs.python.org/3/tutorial/datastructures.html#more-on-lists

Basic Python Learning (vi)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.