# Lecture 14: Nested Lists, Tuples, And Dictionaries

2y ago
35 Views
1,021.61 KB
25 Pages
Last View : 1m ago
Transcription

ture 14: Nested Lists,Tuples, and Dictionaries(Sections 11.1-11.5, 12.1-12)CS 1110Introduction to Computing Using Python[E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner, C. Van Loan, W. White]

Announcements A3 Tentative release date: Mon Mar 19-Thu Mar22; tentative time for completion: somewherebetween 1 and 2 weeks. Similar to A3 fromSpring 2017. Prelim 1 Grading this weekend. Grades willcome out before the drop deadline.2

Next week: Recursion Tuesday and Thursday: Recursion. Reading: 5.8-5.103

Nested Lists Lists can hold any objects Lists are objects Therefore lists can hold other lists!b [3, 1]c [1, 4, b]a [2, 1]x [1, a, c, 5]x[1]x[2]x[2][2]x [1, [2, 1], [1, 4, [3, 1]], 5]x[0]x[1][1]x[2][0]x[2][2][0]4

Two Dimensional ListsTable of DataImages0 1 2 30 5 4 7 31 4 8 9 72 5 1 2 33 4 1 2 94 6 7 8 00 1 2 3 4 5 6 7 8 9 10 1112Each row, colhas a value0123456789101112Each row, col hasan RGB valueStore them as lists of lists (row-major order)d ]5

Overview of Two-Dimensional Lists Access value at row 3, col 2:d[3][2] Assign value at row 3, col 2:d[3][2] 8 Number of rows of d:0 1 2 3d0 5 4 7 31 4 8 9 72 5 1 2 33 4 1 2 94 6 7 8 0§ len(d) Number of cols in row r of d:§ len(d[r])6

How Multidimensional Lists are Stored b [[9, 6, 4], [5, 7, 7]]964577bid1id101id2id3id2id30 91 62 40 51 72 7 b holds id of a one-dimensional list§ Has len(b) elements b[i] holds id of a one-dimensional list§ Has len(b[i]) elements7

Ragged Lists: Rows w/ Different Length b 0128958

Slices and Multidimensional Lists Only “top-level” list is copied. Contents of the list are not altered b [[9, 6], [4, 5], [7, 7]]bid1xid5id2id1012x b[:2]id20196id3id4id401id5id30101id2id345779

Slices & Multidimensional Lists (Q1) Create a nested list What is now in x? b [[9,6],[4,5],[7,7]] Get a slice x b[:2] Append to a row of x x[1].append(10)A: [[9,6,10]]B: [[9,6],[4,5,10]]C: [[9,6],[4,5,10],[7,7]]D: [[9,6],[4,10],[7,7]]E: I don’t know10

Slices & Multidimensional Lists (A1) Create a nested list What is now in x? b [[9,6],[4,5],[7,7]] Get a slice x b[:2] Append to a row of x x[1].append(10)A: [[9,6,10]]B: [[9,6],[4,5,10]]C: [[9,6],[4,5,10],[7,7]]D: [[9,6],[4,10],[7,7]]E: I don’t know11

Slices & Multidimensional Lists (Q2) Create a nested list What is now in b? b [[9,6],[4,5],[7,7]] Get a slice x b[:2] Append to a row of x x[1].append(10) x now has nested listA: [[9,6],[4,5],[7,7]]B: [[9,6],[4,5,10]]C: [[9,6],[4,5,10],[7,7]]D: [[9,6],[4,10],[7,7]]E: I don’t know[[9, 6], [4, 5, 10]]12

Slices & Multidimensional Lists (A2) Create a nested list What is now in b? b [[9,6],[4,5],[7,7]] Get a slice x b[:2] Append to a row of x x[1].append(10) x now has nested listA: [[9,6],[4,5],[7,7]]B: [[9,6],[4,5,10]]C: [[9,6],[4,5,10],[7,7]]D: [[9,6],[4,10],[7,7]]E: I don’t know[[9, 6], [4, 5, 10]]13

Data Wrangling: Transpose Idea12135734246856784 lists: 2 elements in each 2 lists: 4 elements in eachHow to transpose? 1st element of each list gets appended to 1st list 2nd element of each list gets appended to 2nd list14

Data Wrangling: Transpose Codedef transpose(orig table):"""Returns: copy of table with rows and columns swappedPrecondition: table is a (non-ragged) 2d List"""numrows len(orig table)numcols len(orig table[0]) # All rows have same no. colsnew table [] # Result accumulatorfor m in list(range(numcols)):row [] # Single row accumulatorfor n in list(range(numrows)):row.append(old table[n][m]) # Build up new rownew table.append(row) # Add new row to new tablereturn new table123 45613524615

Tuplesstrings:lists:immutable sequences of charactersmutable sequences of any objects“tuple” generalizes “pair,”“triple,” “quadruple,” tuples:immutable sequences of any objects Tuples fall between strings and lists§ write them with just commas: 42, 4.0, ‘x’§ often enclosed in parentheses: (42, 4.0, ‘x’)Conventionally use lists for: long sequences homogeneous sequences variable length sequencesConventionally use tuples for: short sequences heterogeneous sequences fixed length sequences16

Returning multiple values Can use lists/tuples to return multiple valuesINCHES PER FOOT 12def to feet and inches(height in inches):feet height in inches // INCHES PER FOOTinches height in inches % INCHES PER FOOTreturn (feet, inches)all inches 68(ft,ins) to feet and inches(all inches)print(You are “ str(ft) ” feet, “ str(ins) ” inches.”)17

Dictionaries (Type dict)Description List of key-value pairs§ Keys are unique§ Values need not be Example: net-ids§§§§net-ids are unique (a key)names need not be (values)js1 is John Smith (class ’13)js2 is John Smith (class ’16)Python Syntax Create with format:{k1:v1, k2:v2, } Keys must be immutable§ ints, floats, bools, strings§ Not lists or custom objects Values can be anything Example:d {'ec1':'Ezra Cornell','ec2':'Ezra Cornell','ela63':'Erik Andersen'}18

Using Dictionaries (Type dict) Access elements like a list d {'ec1':'Ezra','ec2':'Ezra','ela63':'Erik'}§ d['ec1'] evaluates to 'Ezra'§ But cannot slice ik'19

Using Dictionaries (Type dict) Dictionaries are mutable§ Can reassign values§ d['ec1'] 'Ellis'd ict'ec1''Ezra''ec2''Ezra''ela63''Erik'20

Using Dictionaries (Type dict) Dictionaries are mutable§ Can reassign values§ d['ec1'] 'Ellis'd ec1'ûdict'Ezra' 'Ellis''ec2''Ezra''ela63''Erik'21

Using Dictionaries (Type dict) Dictionaries are mutable§§§§Can reassign valuesd['ec1'] 'Ellis'Can add new keysd['aa1'] 'Allen'd ec1'ûdict'Ezra' 'Ellis''ec2''Ezra''ela63''Erik'22

Using Dictionaries (Type dict) Dictionaries are mutable§§§§Can reassign valuesd['ec1'] 'Ellis'Can add new keysd['aa1'] 'Allen'd llen'}did8id8'ec1'ûdict'Ezra' 'Ellis''ec2''Ezra''ela63''Erik''aa1''Allen'23

Using Dictionaries (Type dict) Dictionaries are mutable§§§§§§Can reassign valuesd['ec1'] 'Ellis'Can add new keysd['aa1'] 'Allen'Can delete keysdel d['ela63']d llen'}did8id8'ec1'ûdict'Ezra' 'Ellis''ec2''Ezra''ela63''Erik''aa1''Allen'24

Using Dictionaries (Type dict) Dictionaries are mutable§§§§§§Can reassign valuesd['ec1'] 'Ellis'Can add new keysd['aa1'] 'Allen'Can delete keysdel d['ela63']d c1''ec2'ûûdict'Ezra' 'Ellis''Ezra'û'ela63''Erik''aa1''Allen'Deleting key deletes both25

Dictionaries (Type dict) Description List of key-value pairs §Keys are unique §Values need not be Example: net-ids §net-ids are unique(a key) §names need not be (values) §js1 is John Smith (class ’13) §js2 is John Smith (class ’16) Python Syntax Create with format:

Related Documents:

Introduction of Chemical Reaction Engineering Introduction about Chemical Engineering 0:31:15 0:31:09. Lecture 14 Lecture 15 Lecture 16 Lecture 17 Lecture 18 Lecture 19 Lecture 20 Lecture 21 Lecture 22 Lecture 23 Lecture 24 Lecture 25 Lecture 26 Lecture 27 Lecture 28 Lecture

The basic structure of a SQL query 1s a query block, which consists pnnclpally of a SELECT clause, a FROM clause, and zero or more WHERE clauses The first query block m a nested . Kim's Algorithms for Processing Nested Queries Km observed that for type-N and type-J nested queries, the nested iteraaon method for processmg nested quenes is .

Python Scipy Data I/O Visualization Python is an object oriented language “In Python, we do things with stuff!” things operations stuff objects Type Example Numbers 128, 3.14, 4 5j Strings ’Rony , "Giovanni’s" Lists [1,"string",2.45] Tuples (1,"string",2.45) Strings, Lists and Tuples are sequences. Strings and Tuples are .

Approximation for New Products, Estimated Elasticities (Median of 6.5) Nested CES, Elasticity 11.5 from Broda and Weinstein (2010) Nested CES, Elasticity 7 from Montgomery and Rossi (1999) Nested CES, Elasticity 4 from Dube et al (2005) Nested CES, Elasticity 2.09 from Handbury (2013) Nested

11 Nested Blocks and Variable Scope Statements can be nested wherever an executable statement is allowed. Nested block becomes a statement. Exception section can contain nested blocks. Scope of an object is the region of the program that can refer to the object. Identifier is visible in the regions in which you can reference the unqualified identifier.

Dictionaries Dictionaries are unordered collections of objects, optimized for quick searching. Instead of an index, objects are identified by their 'key'. Eachitemwithin a dictionary is a 'key':'value' pair. Equivalent to hashes or associative arrays in other languages. Like lists and tuples, they can be variable-length,

Lecture 1: A Beginner's Guide Lecture 2: Introduction to Programming Lecture 3: Introduction to C, structure of C programming Lecture 4: Elements of C Lecture 5: Variables, Statements, Expressions Lecture 6: Input-Output in C Lecture 7: Formatted Input-Output Lecture 8: Operators Lecture 9: Operators continued

Lecture 1: Introduction and Orientation. Lecture 2: Overview of Electronic Materials . Lecture 3: Free electron Fermi gas . Lecture 4: Energy bands . Lecture 5: Carrier Concentration in Semiconductors . Lecture 6: Shallow dopants and Deep -level traps . Lecture 7: Silicon Materials . Lecture 8: Oxidation. Lecture