Summary of Python indexes and slices

Introduction

I don't know what number to brew, but it's important to experience it for yourself and write it in your own words.

Index (especially for strings)

You can treat it like a one-dimensional array in which each character is stored just by defining a character string normally.

python


letters="ABCDEFG"

#What is the third (counting from 0)?
letters[3]  # 'D'

You can also use the minus to count from behind. When it is in normal order, it counts from 0, but when it is from the back, it ends with -1. Not -0. Naturally?

python


#What is the second from the back?
letters[-2]  # 'F'

It is also possible to extract character strings one by one as a one-dimensional array.

Source


for letter in letters:
  print (letter)

result


A
B
C
D
E
F
G

It's a bit off the point, but it's useful to remember the enumerate function. You can get the index and the element at the same time. It is not difficult to get the same result without using this. It's a readability issue. Or they are considering porting to other languages that do not have this function. I strongly agree with the opinion that it's unpleasant to get values for multiple variables at once, but you should get used to it.

Source using the enumerate function


for i,letter in enumerate(letters):
  print (i,letter)

Sources that do not use the enumerate function


for i in range(len(letters)):
  print (i,letters[i])

The result is the same


0 A
1 B
2 C
3 D
4 E
5 F
6 G

Petit Computer, which has a Showa scent, also has a hidden index specification for character strings, which is not specified in the manual (there is no enumerate function). The image below is a composite, and 3DS Petitcon No. 3 cannot be executed on the lower screen while displaying the list on the upper screen. I do not care.

petitcom3.png

The reason why it's so easy to find out if a string contains a particular string may be due to the specification that the string can also be used as a one-dimensional array.

Source


if "CD" in "ABCDEFG":  #I made it visible because it is difficult to understand what I am doing with variables
  print ("Will be included")
else:
  print ("Not included")

result


Will be included

slice

Slice is a trick that can take out a part of the array. Expressed as [start: end: step]. If start is omitted, it will be from the beginning, if end is omitted, it will be until the end, and if step is omitted, step = 1. Like the index, it counts from 0 and does not include the value specified for end.

Slice into a string / one-dimensional array

Basic

python


#Redefined for ease of confirmation
letters="ABCDEFG"

#Specify start and end, omit step
letters[3:5]  # 'DE'

It seems inconvenient that the index specified by end is not actually included, but it also has an advantage.

python


#Redefined for ease of confirmation
letters="ABCDEFG"

#Specify only end = so-called left function
letters[:4]  # 'ABCD'

#Specify only start = from the specified position to the end
letters[4:]  # 'EFG'

In this way, you can split the array by specifying one index.

Specify minus

Let's get used to the negative treatment.

python


#Redefined for ease of confirmation
letters="ABCDEFG"

#3rd character from the back (specified by index instead of slice, already mentioned)
print(letters[-3])  # 'E'

#Specify only start = so-called right function from "third character from the back" to the end
print(letters[-3:])  # 'EFG'

#Specify only end = from the beginning to "third character from the back"
print(letters[:-3])  # 'ABCD'

#It will be used less frequently, but of course both can be negative. Pay attention to the size relationship.
print(letters[-5:-3])  # 'CD'

mid function / left function / right function

You can also create your own mid function using slices. It may not be necessary to make it a function, but let's also create a left function and a right function. The reason why 0 is specified as the default value of length is to output "from the specified position to the end" when lengh is omitted. -1 is for counting the first character as the first character instead of the 0th character. By the way, in Excel, the behavior was different between the MID function of the worksheet function and the Mid function of VBA.

python


def left(text, length):
  return text[:length]

def right(text, length):
  return text[-length:]

def mid(text, pos, length=0):
  if not length:
    length=len(text)
  return text[pos-1:pos+length-1]

Specify step

When step is specified, it becomes like this. First, get it normally in step 2.

python


#Redefined for ease of confirmation
letters="ABCDEFG"

letters[1:5:2]  # 'BD'

#This is such a mechanism.
# ABCDEFG
# 0123456
#  ◯ ◯ ×
#2nd argument=Since it is 5, it does not include the 5th character

If you specify minus for step, it will proceed in the opposite direction. Since it goes in the opposite direction, the end must be smaller and the start must be larger.

python


letters[5:1:-2]  # 'FD'

I thought that step is negative is not such an irregular usage, but ** Start and end are all specified and step is set to -1, that is, if :: -1 is set, all elements are in reverse order ** It is good to remember this movement because it is used frequently. As for what to use, the image read by imread of OpenCV has the color stored in BGR, but it can be used when converting this to RGB. OpenCV also has a color conversion function, but this one is smarter.

Source


print (letters)
print (letters[::-1])

result


ABCDEFG
GFEDCBA

Two-dimensional array

I really wanted to talk from here. First, make a two-dimensional array. I suddenly stumbled upon the story of ** last time **.

Source


#promise
import numpy as np

#Height and width
H,W = 5,6

#First create an empty array with only the size defined
arr=np.full((H,W),"",dtype=object)

#Define values like Excel cell names
letters="ABCDEFG"
for c in range(W):
  for r in range(H):
    arr[r,c]=letters[c]+str(r)

print (arr)

result


[['A0' 'B0' 'C0' 'D0' 'E0' 'F0']
 ['A1' 'B1' 'C1' 'D1' 'E1' 'F1']
 ['A2' 'B2' 'C2' 'D2' 'E2' 'F2']
 ['A3' 'B3' 'C3' 'D3' 'E3' 'F3']
 ['A4' 'B4' 'C4' 'D4' 'E4' 'F4']]

If you specify it by index normally, it will be like this. I write it many times, but the count starts from 0.

python


r,c=2,1
arr[r,c]  # 'B2'

If you specify slices for rows and columns, it will look like this. Since the basic is [start: end], you can use [r1: r2, c1: c2] as the coordinate tick, but you should remember it by writing ** [r: r + h, c: c + w] **. think.

Source


r,c = 2,1  #Starting row and column
h,w = 3,4  #Range height and width
print(arr[r:r+h, c:c+w])

result


[['B2' 'C2' 'D2' 'E2']
 ['B3' 'C3' 'D3' 'E3']
 ['B4' 'C4' 'D4' 'E4']]

The array of the specified number of rows and columns has been successfully acquired.

Index and slice matching technique, or something to note

** Index specification returns one element **, but ** slice returns a part of the array **. Even if it's one row and one column.

Source


r,c = 2,1  #Starting row and column
h,w = 1,1  #Range height and width
print ("index",arr[r, c])
print ("slice",arr[r:r+h, c:c+w])

python


Index B2
slice[['B2']]

That doesn't seem to be a string, though.

Source


#Redefined for ease of confirmation
letters="ABCDEFG"

print ("index",letters[3])
print ("slice",letters[3:3+1])

result


Index D
Slice D

Specifying one of the two-dimensional array matrices as an index and the other as a slice results in a one-dimensional array. It's a one-dimensional array, or just an enumeration or list.

Source


r=3
print (arr[r,:])  #All columns are specified

c=4
print (arr[:,c])  #All lines are specified

result


['A3' 'B3' 'C3' 'D3' 'E3' 'F3']
['E0' 'E1' 'E2' 'E3' 'E4']

I wrote the result of slicing 1 row 1 column above, but let me give you a more practical example. If one row of the two-dimensional array is specified by slicing and the column is also sliced, it will be as follows. The bracket is doubled. It is a two-dimensional array with 1 row and w columns.

Source


r=3
print (arr[r:r+1,:])

result


[['A3' 'B3' 'C3' 'D3' 'E3' 'F3']]

If you specify the row as a slice and specify one column as a slice, it becomes a two-dimensional array with h rows and 1 column.

Source


c=4
print (arr[:,c:c+1])

result


[['E0']
 ['E1']
 ['E2']
 ['E3']
 ['E4']]

Use slice steps in a two-dimensional array

Only an example of flipping with :: -1 instead of the normal step usage is shown.

Source


print("Original shape")
print(arr)
print("First argument = invert line")
print(arr[::-1])
print("Second argument = Invert column The first argument is all specified.::But okay:But it is good")
print(arr[::, ::-1])
print("Invert both rows and columns")
print(arr[::-1, ::-1])

result


Original shape
[['A0' 'B0' 'C0' 'D0' 'E0' 'F0']
 ['A1' 'B1' 'C1' 'D1' 'E1' 'F1']
 ['A2' 'B2' 'C2' 'D2' 'E2' 'F2']
 ['A3' 'B3' 'C3' 'D3' 'E3' 'F3']
 ['A4' 'B4' 'C4' 'D4' 'E4' 'F4']]
First argument = invert line
[['A4' 'B4' 'C4' 'D4' 'E4' 'F4']
 ['A3' 'B3' 'C3' 'D3' 'E3' 'F3']
 ['A2' 'B2' 'C2' 'D2' 'E2' 'F2']
 ['A1' 'B1' 'C1' 'D1' 'E1' 'F1']
 ['A0' 'B0' 'C0' 'D0' 'E0' 'F0']]
Second argument = Invert column The first argument is all specified.::But okay:But it is good
[['F0' 'E0' 'D0' 'C0' 'B0' 'A0']
 ['F1' 'E1' 'D1' 'C1' 'B1' 'A1']
 ['F2' 'E2' 'D2' 'C2' 'B2' 'A2']
 ['F3' 'E3' 'D3' 'C3' 'B3' 'A3']
 ['F4' 'E4' 'D4' 'C4' 'B4' 'A4']]
Invert both rows and columns
[['F4' 'E4' 'D4' 'C4' 'B4' 'A4']
 ['F3' 'E3' 'D3' 'C3' 'B3' 'A3']
 ['F2' 'E2' 'D2' 'C2' 'B2' 'A2']
 ['F1' 'E1' 'D1' 'C1' 'B1' 'A1']
 ['F0' 'E0' 'D0' 'C0' 'B0' 'A0']]

I can't remember this kind of thing unless I try it myself.

Next time preview

I wanted to enter the OpenCV image from here, but I was exhausted. Next time I'll talk about images.

Recommended Posts

Summary of Python indexes and slices
Summary of Python arguments
Correspondence summary of array operation of ruby and python
Summary of the differences between PHP and Python
Installation of Python3 and Flask [Environment construction summary]
I / O related summary of python and fortran
Summary of python file operations
Summary of Python3 list operations
Source installation and installation of Python
Python --Explanation and usage summary of the top 24 packages
[Python] Type Error: Summary of error causes and remedies for'None Type'
Summary of date processing in Python (datetime and dateutil)
Environment construction of python and opencv
Python Summary
The story of Python and the story of NaN
Installation of SciPy and matplotlib (Python)
[python] Summary of how to retrieve lists and dictionary elements
Python summary
Summary of Hash (Dictionary) operation support for Ruby and Python
Coexistence of Python2 and 3 with CircleCI (1.0)
Reputation of Python books and reference books
[OpenCV; Python] Summary of findcontours function
Summary of differences between Python and PHP (comparison table of main items)
Installation of Visual studio code and installation of python
[Python] Summary of how to use pandas
Extraction of tweet.js (json.loads and eval) (Python)
Summary of various for statements in Python
[Python] Summary of array generation (initialization) time! !! !!
Connect a lot of Python or and and
[Python2.7] Summary of how to use unittest
Summary of modules and classes in Python-TensorFlow2-
Summary of built-in methods in Python list
Summary of useful techniques for Python Scrapy
Summary of how to use Python list
Easy introduction of python3 series and OpenCV3
[Python] Various combinations of strings and values
[Python2.7] Summary of how to use subprocess
Axis option specification summary of Python "numpy.sum (...)"
Idempotent automation of Python and PyPI setup
Full understanding of Python threading and multiprocessing
Project Euler # 1 "Multiples of 3 and 5" in Python
About python slices
Introduction of Python
Python tutorial summary
[Python] Summary of conversion between character strings and numerical values (ascii code)
Basics of Python ①
Basics of python ①
Copy of python
python related summary
Python basics summary
Introduction of Python
Summary of OSS tools and libraries created in 2016
Summary of how to import files in Python 3
The answer of "1/2" is different between python2 and 3
Specifying the range of ruby and python arrays
Summary of how to use MNIST in Python
Compare the speed of Python append and map
[Python] Chapter 02-01 Basics of Python programs (operations and variables)
Implementation of TRIE tree with Python and LOUDS
Links and memos of Python character code strings
[Python] Summary of S3 file operations with boto3