Ai05 2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 54

Chapter 05.

Strings and
arrays
Table of contents

5.1 String

5.2 Type of array


5.1 String

Big Data Analytics &


Artificial Intelligence
Starting with Python
String

▪ Quote
– Strings can use both double and single quotes

– Use double quotes for strings that need to be printed in single quotes.

– Question?
Read string

▪ Index
– When you store a string in a variable, an array is automatically created.

– If there are n storage locations, the indices range from 0 to n-1.

– Python also provides an indexing method that starts with -1 from the last item and
decreases by 1.
String slicing

▪ Argument format [start:end+1:step]

▪ When there is 1 argument

▪ When there are 2 arguments

▪ When there are 3 arguments


String slicing

▪ If argument is omitted
– If there is only one colon (:)

– If there are two colons (:)


Merging of strings

If you put a '+' sign between two strings, the preceding and following
strings are merged.
String functions (methods)

▪ len() function
– Returns the length of the string (object) in parentheses

▪ method call
– Call various methods (functions) provided by string-type objects by
connecting them with dots (.)
String functions (methods)

▪ information collection

Question?
find vs rfind?

▪ in
– Determine whether a specific character or string exists in that string
String functions (methods)

▪ Changing information
– Methods (functions) that can modify the contents of a string

Swapcase ?

– Execute the following statement to modify the original contents:


String functions (methods)

▪ Information segmentation
– Method to remove whitespace from string
Randomizing arrays

▪ choice()
– print random characters

▪ shuffle()
– In fact, the order of the array is reversed and stored
5.2 Types of Arrays

Big Data Analytics &


Artificial Intelligence
Starting with Python
Array data structure
▪ Array data structure
– String type, Unicode string type, list, tuple, byte array, xrange()
– Store multiple data in one variable and access them conveniently

▪ Mutable and immutable


Mutable data types Immutable data types
list int, float
dict bool
set str
tuple

– immutable - Integer types are immutable

Difference between mutable and


immutable in python? (tutorialspoi
nt.com)
List

▪ List
– Multiple data types can also be entered
– Square brackets ([]) are used and each item is separated by a
comma (,)

▪ One-dimensional list
Copy of list
▪ Copy of list
- If you copy a to b and change the value stored at index 0 of b

– Two different variables pointing to the same object

– Modified up to the array of a


Slicing

▪ Slicing the list


– Same as string slicing
– Lists store various data such as integers, real numbers,
and strings.
– Structure [start:end+1:step]
Merge and Insert in Lists

▪ Merge multiple variables

▪ Merge multiple lists


Insert an element into a list
▪ append() method
– Accepts 1 argument as input
– You can additionally paste that value at the end of the list.

– An example of repeatedly entering an integer value one by one in an


empty list
Insert element into list

▪ insert() method
– The first of the two input arguments is an index number
– Enter the value of the second factor at the position just before
the index number
List comprehension

▪ List comprehension
– For all elements stored in a specific list, only elements that meet the
condition are selectively added.
– After reading the elements of the list (①) into i(②) and testing the value in
the conditional expression (③), if the result is true, i(④) is entered into the
list.
[i for i in (List name) if (conditional expression)]
Delete an item in a list

▪ Delete with the del statement


– Delete the item corresponding to the specified location

– Use the slice function to delete multiple items


Delete an item in a list

▪ Delete with pop() function


– Delete function provided by list object

– If you enter an input value, it is recognized as an index and the


item is deleted.
Delete an item in a list

▪ Delete with empty list ([])


Presence

▪ in
– Check if a string contains a specific character

▪ not in
– Example: Checking if a specific fruit is not present in the list
fruits
Repetition of elements

– Repeat the element twice and output:

– Multiply each element by 2:


len() and count()

▪ len()
– Count the number of elements

▪ count()
– Measure the number of specific values
Find your index number

▪ index()
– Returns the index number of the first occurrence of x in the
array list

– In the nums list, 3 is at indexes 2 and 5, but index(3) returns the


first index.
Sorting

▪ sort()

▪ reverse() (in reverse order)


Two-dimensional list
▪ Example: fruitdb list

– fruits: one-dimensional list


– fruitdb: 2D list (3x2 matrix)

– Read and print the contents stored in a specific location


Two-dimensional list
– Example: Create a new index list by gathering only the contents stored at
index 1 of all lists stored in the 2-dimensional list record.

– Example: Extract only items with the number of elements 2 from mylist and
create newlist
Tuple
▪ Tuple
– Arrays that cannot be changed after initialization
– Items are connected with a comma (,) in the format enclosed in
parentheses (())
– parentheses can be omitted
– Can contain strings, numbers, tuples, and lists
– Indexing, slicing, and method functionality are similar to lists.
Tuple

▪ indexing, slicing

▪ Cannot change once entered

▪ Superposition
Tuple

▪ Tuple containing list

– Tuples cannot contain new values

– A list that exists as an element inside a tuple can be modified


Tuple

▪ List containing tuples


– It is possible to modify the elements of the list (not the contents
of the tuple)
Functions of tuples compared to lists

▪ Slicing ▪ Absorption

Multiple variables can be


packed or unpacked into a
single tuple.

No ability to insert data with


append() or insert() or delete items
using the del command and pop()
method
Functions of tuples compared to lists

▪ Existence ▪ Counting the number of


elements

▪ reiteration
Functions of tuples compared to lists

▪ search function
– frequency check

– find index number


Two-dimensional tuple

Construct the elements of a tuple in two dimensions


Dictionary

▪ Dictionary dictionary
– A pair of key and value
– index by key (string, number, tuple)
– A dictionary must contain unique keys
– Cannot be used as a key if it contains an object that can be
directly or indirectly modified
Creating and inserting dictionaries

▪ Creation of a dictionary
– Curly braces { } create an empty dictionary
▪ Insertion
– Input as a set of unordered key:value pairs in the form of {key:value}
– Instead of using sequential numbers for indexes, use keys as if they were
indexes.
– If there are two or more items in the dictionary, they are connected by
commas (,)
Dictionary

▪ Entering multiple pieces of information into one


statement

▪ indexing and slicing


– Both indexing and slicing do not work and generate an error
Delete dictionary entry

▪ Delete dictionary entry


– del command
Dictionary entry search
▪ Dictionary entry search
– Key in Dictionary: True if key value exists, False otherwise
– None --- get(): Returns the value of the key if it exists, or None if it does not.
– keys(): return all keys
– values(): return all values
– items(): return all key:value pairs
Merge dictionary

▪ Merge dictionary
– Using the update() method
Create a dictionary with another array

▪ Create a dictionary with another array


– You can use the dict() function (constructor) to create an array of key:value
pairs in dictionary format.
– Lists and tuples can also be written as dictionaries.

– Use an equal sign ('=') to associate a key with a corresponding value


set

▪ (Set)
– Composed of non-duplicate and ordered elements
– Use { } symbols as in a dictionary and separate elements with commas (,)
– Unlike a dictionary, a type with only keys and no values

– A list or tuple can be created in the form of a set using the set() function
Adding and deleting elements of a set

▪ Add
– add()

– update()

▪ Delete
– remove()
– pop()
set

▪ presence or absence
– Use 'in' or 'not in' to check if the corresponding value is a
member
set operation

Operator Meaning
| union
& intersection
- difference
^ Symmetric difference
Relational Operators on Sets

Operator Meaning

<= Check if all elements of the set on the left are on the right

< Check if all elements of the set on the left are on the right
However, the two must not be the same
>= Check if all elements of the set on the right are on the left

> Check if all elements of the set on the right are on the left
However, the two must not be the same
Big data analytics example

– training_data: input data (2-dimensional list)


– fruit_counts() Counts the number of fruits stored in the input
data and stores the information in dictionary format

Question?
{'apple': 2, 'grape': 2, 'lemon': 1}

You might also like