1, implementation transpose matrix:
#矩阵的转置 jz=[[1,2,3],[4,5,6],[7,8,9]] print(jz) for i,row in enumerate(jz): for j,col in enumerate(row): if i<j: jz[i][j],jz[j][i]=jz[j][i],jz[i][j] print(jz)
#enumerate usage:
Syntax: the enumerate ( Sequence , [ Start = 0 ])
- sequence - a sequence, an iterator, or other objects to support iteration.
- start - start index position.
Example:
>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> List ( the enumerate ( Seasons , Start = 1 ) ) # 1 starts from index
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
Another method to achieve:
#矩阵的转置 jz=[[1,2,3],[4,5,6],[7,8,9]] print(jz) for i in range(len(jz)): for j in range(i): jz[i][j],jz[j][i]=jz[j][i],jz[i][j] print(jz)
Irregular matrix transpose implementation:
# Irregular length transposed matrix JZ = [[l, 2,3], [4,5,6 ]] Print (JZ) T = [] for Row in JZ: for I, COL in the enumerate (Row): IF len (t) <I +. 1: # JZ odd row number will add t t.append ([]) t [I] .append (COL) Print (t)
2, 10 randomly generated numbers (less than 21), there are several statistical duplicate numbers, namely what; statistically repeated a few figures, what are:
Import Random the nums = [] for _ in Range (10 ): nums.append (random.randrange ( 21 is )) Print (the nums) S, D = [], [] # are used to hold the same few figures and different few figures lenth = len (the nums) State = [0] * lenth # used for marking, and marking the location of duplicate numbers for I in Range (lenth): # a first layer of elements for each cycle traversal flag = False # each element must be compared before to re-flag initial value IF State [i] == 1: # If the i-th element has been repeated, then do not compare, depending on the back of the state [j ] = 1 and State [I] = 1 Continue forJ in Range (i +. 1, lenth): # For each element i in element i to be behind position compared IF State [J] ==. 1 : Continue IF the nums [i] == the nums [J]: flag = True # repeated, assigned to the flag is True, and this position is marked state. 1 state [J] =. 1 IF flag: s.append (the nums [I]) state [I] =. 1 the else : d.append ( the nums [I]) Print ( " Same has the Array = {{0}}. 1 " .format (S, len (S))) Print ( " Different has the Array = {{0}}. 1 " .format (D, len (D)))
result:
[14, 3, 9, 12, 7, 9, 11, 17, 11, 17] same Array=[9, 11, 17] has 3 different Array=[14, 3, 12, 7] has 4