Beginners python, a small margin of a few problems:
There is a list
A = [1, 2, 3, 4, 5, 6]
Please put a according to
0, 1
1, 2
2, 3
3, 4
4, 5
5, 6
Print output,
2. Reverse a list to [6, 5, 4, 3, 2, 1]
3. Select the even number in a *2, the result is [4, 8, 12]
Basically achieve:
Copy Code code as follows:
a=[1,2,3,4,5,6]
For I in A:
Print A.index (i), ', ', I
A.reverse ();
Print a
For I in A:
If i%2==0
Print i*2
Although all finished, but the small margin said the answer is not good, he replied
Copy Code code as follows:
For k,v in Enumerate (a):
Print K,v
Print A[::-1]
Print [i*2 for i in a if not i%2]
At that time I was dumbfounded, and then the edge of the road and a problem:
Create a list of 200 random positive integers (1~15)
Count the occurrences of positive integers and sort the output
At the beginning, it is not clear random unexpectedly also import ....
Then it took me a long time to do it:
Copy Code code as follows:
>>> Import Random
>>> mylist = [Random.randint (1,15) for I in range (1,200)]
>>> 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)]
Margin comments on the cycle, you can use get such as
Copy Code code as follows:
For I in MyList:
S[i]=s.get (i,0) +1
Then said sorted can have from the big to small inverted row, and then looked for information, found that you can
Sorted (D.items (), Cmp=lambda x,y:cmp (x[1],y[1)), reverse=true)