When I was a beginner in python, I had a few questions:
There is a list
A = [1, 2, 3, 4, 5, 6]
Set a
0, 1
1, 2
2, 3
3, 4
4, 5
5, 6
Print Output,
2. Sort a list in reverse order to [6, 5, 4, 3, 2, 1]
3. Pick out * 2 from the even number in a and the result is [4, 8, 12].
Basically:Copy codeThe Code is as follows: a = [1, 2, 3, 4, 5, 6]
For I in:
Print a. index (I), ',', I
A. reverse ();
Print
For I in:
If I % 2 = 0
Print I * 2
Although all of them have been completed, xiaoyuan said that the answer is not good and he replied in this way.Copy codeThe Code is as follows: for k, v in enumerate ():
Print k, v
Print a [:-1]
Print [I * 2 for I in a if not I % 2]
At that time, I was dumpfounded, and then I had another question:
Create a 200 random positive integer (1 ~ 15) list
Count the occurrence times of positive integers and sort the output results.
At the beginning, it was unclear that random had to import ....
It took a long time to make it:Copy codeThe Code is as follows: >>> import random
>>> Mylist = [random. randint (1,200) for I in range ()]
>>> S = {}
>>> For I in mylist:
If not s. has_key (I ):
S [I] = 0
Else:
S [I] + = 1
>>> Cmplist = sorted (s. items (), key = lambda (d): d [1])
>>> Result = cmplist [:-1]
>>> Print result
[(8, 20), (13, 19), (12, 16), (9, 15), (6, 15), (3, 14), (2, 12), (14, 11), (4, 11), (15, 10), (7, 10), (11, 9), (5, 9 ), (1, 9), (10, 4)]
You can use Get, for exampleCopy codeThe Code is as follows: for I in mylist:
S [I] = s. get (I, 0) + 1
Then I said sorted can have a descending order from large to small. Later I looked for the information and found that I could do this.
Sorted (d. items (), cmp = lambda x, y: cmp (x [1], y [1]), reverse = True)