|
| 1 | +>>> a = ['a', 'b', 'c', 'd', 'e'] |
| 2 | +>>> for index, item in enumerate(a): print index, item |
| 3 | +... |
| 4 | +0 a |
| 5 | +1 b |
| 6 | +2 c |
| 7 | +3 d |
| 8 | +4 e |
| 9 | + |
| 10 | + |
| 11 | + |
| 12 | + |
| 13 | +#convert a list to string: |
| 14 | + |
| 15 | +list1 = ['1', '2', '3'] |
| 16 | +str1 = ''.join(list1) |
| 17 | + |
| 18 | +Or if the list is of integers, convert the elements before joining them. |
| 19 | + |
| 20 | +list1 = [1, 2, 3] |
| 21 | +str1 = ''.join(str(e) for e in list1) |
| 22 | + |
| 23 | + |
| 24 | + |
| 25 | +#FIND method |
| 26 | + |
| 27 | +str.find(str2, beg=0 end=len(string)) |
| 28 | + |
| 29 | +Parameters |
| 30 | +str2 -- This specifies the string to be searched. |
| 31 | +beg -- This is the starting index, by default its 0. |
| 32 | +end -- This is the ending index, by default its equal to the lenght of the string. |
| 33 | + |
| 34 | +Return Value |
| 35 | +This method returns index if found and -1 otherwise. |
| 36 | + |
| 37 | +str1 = "this is string example....wow!!!"; |
| 38 | +str2 = "exam"; |
| 39 | + |
| 40 | +print str1.find(str2); |
| 41 | +print str1.find(str2, 10); |
| 42 | +print str1.find(str2, 40); |
| 43 | + |
| 44 | +#15 |
| 45 | +#15 |
| 46 | +#-1 |
| 47 | + |
| 48 | + |
| 49 | + |
| 50 | + |
| 51 | + |
| 52 | +#2D LIST PYTHON |
| 53 | + |
| 54 | +# Creates a list containing 5 lists initialized to 0 |
| 55 | +Matrix = [[0 for x in range(5)] for x in range(5)] |
| 56 | +You can now add items to the list: |
| 57 | + |
| 58 | +Matrix[0][0] = 1 |
| 59 | +Matrix[4][0] = 5 |
| 60 | + |
| 61 | +print Matrix[0][0] # prints 1 |
| 62 | +print Matrix[4][0] # prints 5 |
| 63 | + |
| 64 | + |
| 65 | +if you have a simple two-dimensional list like this: |
| 66 | + |
| 67 | +A = [[1,2,3,4], |
| 68 | + [5,6,7,8]] |
| 69 | +then you can extract a column like this: |
| 70 | + |
| 71 | +def column(matrix, i): |
| 72 | + return [row[i] for row in matrix] |
| 73 | +Extracting the second column (index 1): |
| 74 | + |
| 75 | +>>> column(A, 1) |
| 76 | +[2, 6] |
| 77 | +Or alternatively, simply: |
| 78 | + |
| 79 | +>>> [row[1] for row in A] |
| 80 | +[2, 6] |
0 commit comments