python里什么是generator object

在python学习过程中查看某个函数的返回值时,蹦出了一条打印:

<generator object bigrams at 0x000001D5B9FC3AC0>

本来预期函数返回的是列表,为什么会出现这个打印呢?

查了下才知道这条打印的含义,直译为“生成器对象bigrams在0x000001D5B9FC3AC0”,也就是说函数返回的不是列表,而是一个“生成器对象”。什么是生成器对象呢 ?

原来生成器对象是一个可以产生数据,可迭代的一个对象。与此相关的还有一个“生成器表达式”概念。

1. 生成器表达式

列表推导的时候一般这么写,这里的mylist是一个列表类型:

>>> mylist = [n for n in range(10)]
>>> mylist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

 如果把这里的"[ ]"换成"( )",就发生了一件神奇的事情,mylist不是列表类型,而是一个“生成器表达式”:

>>> mylist = (n for n in range(10))
>>> mylist
<generator object <genexpr> at 0x000001D5B9FC3A50>

 这里的打印说明mylist是一个<genexpr>生成器表达式(generator expression)。突然感觉python高深莫测。

怎么查看生成器表达式的结果呢?有两种方式:

第一种用list:

>>> list(mylist)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

第二种用for循环:

>>> for n in mylist:
...     print(n)
...
0
1
2
3

2. 生成器对象

函数里使用yield关键字,这个函数就会返回生成器对象。下面代码里的g就是生成器对象:

>>> def num(start, stop, increment):
...     x = start
...     while x < stop:
...         yield x
...         x += increment
...
>>> g = num(0, 10, 1)
>>> g
<generator object num at 0x000001D5B9FC3E40>
>>> list(g)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

总结:目前我能体会到的使用生成器的好处就是不用一次性产生完整的列表数据,而是通过循环每次获取下一个数据来使用,如果数据量很大的话,这可以节省内存空间。由于工作中没有用到生成器,其他的好处还体会不到。

  • 46
    点赞
  • 74
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
CHAPTER 1 About Python ............................................................................................1 What Is Python? ................................................................................................................1 A Brief History of Python ................................................................................................2 Interpreters Versus Compilers .......................................................................................5 When to Use (or Not Use) an Interpreted Language .........................................8 Understanding Bytecodes ......................................................................................10 Why Use Python? ...........................................................................................................11 Object-Oriented ........................................................................................................11 Cross Platform ..........................................................................................................11 Broad User Base .......................................................................................................11 Well Supported in Third-Party Tools ...................................................................12 Good Selection of Tools Available ........................................................................12 Good Selection of Pre-built Libraries ..................................................................12 Where Is Python Used? .................................................................................................13 How Is Python Licensed? ..............................................................................................13 Where Do I Get Python? ...............................................................................................14 Installing Python ............................................................................................................14 Getting Information on Python ..................................................................................16 Python Communities .....................................................................................................17 Other Software ................................................................................................................18 And Now for Something Completely Different… ....................................................18 CHAPTER 2 Python Language Overview .................................................................19 Python Syntax .................................................................................................................20 Comments .................................................................................................................20 Indentation ...............................................................................................................20 Contents TABLE OF} vii Q Q Q Python Reserved Words ................................................................................................24 Decision Making and Iteration Keywords ..........................................................25 Debugging Keywords ..............................................................................................27 Package and Module Handling Keywords .........................................................27 Exception Handling Keywords ..............................................................................29 General Language Keywords .................................................................................31 Other Keywords ........................................................................................................32 Variable Usage ................................................................................................................34 The Continuation Variable ....................................................................................36 Watching Out for Spelling Mistakes! ..................................................................37 Predicates .........................................................................................................................38 Identifier Scope ...............................................................................................................39 Operators .........................................................................................................................42 Modulo Operator .....................................................................................................44 Exponential Operator .............................................................................................46 Logical Operators ....................................................................................................46 Comparative Operators ..........................................................................................49 Bitwise Operators ....................................................................................................51 Membership Operators and String Operators ..................................................53 Identity Operators ...................................................................................................53 In Conclusion ..................................................................................................................53 CHAPTER 3 Tools ..........................................................................................................55 IDLE ...................................................................................................................................55 File Menu ...................................................................................................................57 The Path Browser Dialog ........................................................................................62 Edit Menu ..................................................................................................................64 Shell Menu .................................................................................................................70 Debug Menu ..............................................................................................................71 The Edit Window ......................................................................................................79 Format Menu ............................................................................................................80 CONTENTS viii Q Q Q Command Line Compiler ..............................................................................................90 Creating Python Files ....................................................................................................93 Documentation ...............................................................................................................95 In Conclusion ..................................................................................................................96 CHAPTER 4 Data Types ...............................................................................................97 Numeric Types ................................................................................................................98 Integers ......................................................................................................................98 Demonstrating Long Integers ...............................................................................99 Octal and Hexadecimal ........................................................................................100 Floating Point Numbers .............................................................................................101 Strings ............................................................................................................................103 String Variables .....................................................................................................103 Concatenating Strings .........................................................................................106 Repeating Strings ..................................................................................................107 Substrings ...............................................................................................................108 Slicing ......................................................................................................................110 String Functions ....................................................................................................111 String Constants ....................................................................................................112 Conversion Functions ...........................................................................................114 Search Functions ...................................................................................................118 Formatting Functions ..........................................................................................120 Escape Sequences ..................................................................................................121 Sequences ......................................................................................................................122 Lists ..........................................................................................................................123 Shared References .................................................................................................128 Tuples .......................................................................................................................128 Dictionaries ............................................................................................................132 Advanced Type .............................................................................................................136 Classes and Objects ..............................................................................................136 Complex Type .........................................................................................................137 Generator Type ......................................................................................................138 CONTENTS ix Q Q Q None Type ...............................................................................................................139 Unicode Type ..........................................................................................................140 In Conclusion ................................................................................................................141 CHAPTER 5 Control Flow .........................................................................................143 Conditionals ..................................................................................................................144 The if Statement ..................................................................................................144 The elif Statement .............................................................................................147 The else Statement .............................................................................................149 Wrapping Up the Conditionals: A Cool Example ...........................................150 Loops ..............................................................................................................................153 The for Loop ..........................................................................................................153 The while Loop .....................................................................................................161 In Conclusion ................................................................................................................164 CHAPTER 6 Input and Output ................................................................................165 User Input ......................................................................................................................165 The input Function ..............................................................................................166 The raw_input Function ....................................................................................168 User Output ...................................................................................................................170 Formatting ..............................................................................................................172 File Input .......................................................................................................................175 File Output ....................................................................................................................177 Closing Files ..................................................................................................................179 Positioning in Files ......................................................................................................180 Directories and Files ...................................................................................................183 The stat Module: File Statistics ..............................................................................186 Command Line Arguments ........................................................................................190 Pickle ..............................................................................................................................192 In Conclusion ................................................................................................................195 CONTENTS x Q Q Q CHAPTER 7 Functions and Modules .....................................................................197 What Is a Function? ....................................................................................................197 Defining Functions in Python ...................................................................................197 What Are Arguments? ................................................................................................200 How Do You Pass an Argument to a Function? ....................................................201 Default Arguments ......................................................................................................203 Variable Default Arguments .....................................................................................205 Keyword Arguments ....................................................................................................206 Returning Values from Functions ............................................................................207 Returning Multiple Values from Functions ...........................................................209 Recursive Functions ....................................................................................................210 Passing Functions as Arguments .............................................................................212 Lambda Functions .......................................................................................................213 Variable Numbers of Arguments to a Function ....................................................215 Variable Scope in Functions ......................................................................................216 Using Modules ..............................................................................................................218 In Conclusion ................................................................................................................219 CHAPTER 8 Exception Handling ............................................................................221 Looking at Exceptions in Python ..............................................................................222 Traceback Example ......................................................................................................223 Understanding Tracebacks ........................................................................................224 Exceptions .....................................................................................................................225 Catching Exceptions with try..except .........................................................226 Multiple except Clauses .....................................................................................229 Blank except Clauses ..........................................................................................231 The else Clauses .........................................................................................................232 The finally Clause ....................................................................................................234 Raising Your Own Exceptions ...................................................................................235 Exception Arguments .................................................................................................237 User-Defined Exceptions ............................................................................................238 Working with the Exception Information ..............................................................239 CONTENTS xi Q Q Q exc_type ................................................................................................................239 exc_value ..............................................................................................................240 Using the with Clause for Files ................................................................................243 Re-throwing Exceptions .............................................................................................244 In Conclusion ................................................................................................................246 CHAPTER 9 Object-Oriented Programming .........................................................247 A Brief History of OOP ................................................................................................247 What Is an Object? ......................................................................................................248 Why Do We Use Objects? ...........................................................................................249 Reuse ........................................................................................................................249 Ease in Debugging .................................................................................................250 Maintainability ......................................................................................................250 The Attributes of Object-Oriented Development .................................................251 Abstraction .............................................................................................................251 Data Hiding ............................................................................................................252 Inheritance .............................................................................................................253 Polymorphism ........................................................................................................255 Terminology ..................................................................................................................256 Class .........................................................................................................................256 Object .......................................................................................................................256 Attribute ..................................................................................................................257 Method ....................................................................................................................258 Message Passing ....................................................................................................259 Event Handling ......................................................................................................260 Derivation ...............................................................................................................260 Coupling ..................................................................................................................261 Cohesion ..................................................................................................................261 Constants ................................................................................................................261 Other Concepts .............................................................................................................262 In Conclusion ................................................................................................................262 CONTENTS xii Q Q Q CHAPTER 10 Classes and Objects in Python ..........................................................265 Python Classes ..............................................................................................................265 Properties ......................................................................................................................267 Attribute Modifying Functions .................................................................................272 Private Attributes ........................................................................................................274 Doc Strings ....................................................................................................................275 Properties ......................................................................................................................277 The self Object ...........................................................................................................279 Methods .........................................................................................................................281 Special Methods ...........................................................................................................283 Initialization ...........................................................................................................283 Termination ............................................................................................................284 String Conversion ..................................................................................................285 Inheritance ....................................................................................................................287 Multiple Inheritance ...................................................................................................291 Using super ..................................................................................................................293 Polymorphism ..............................................................................................................295 Exception Classes .........................................................................................................297 Iterators .........................................................................................................................299 Operator Overloading .................................................................................................301 In Conclusion ................................................................................................................304 CHAPTER 11 The Python Library ..............................................................................305 Containers .....................................................................................................................305 Working with the deque Class ...........................................................................306 Math ................................................................................................................................312 Complex Math ..............................................................................................................313 Types ...............................................................................................................................315 Strings ............................................................................................................................318 Regular Expressions ....................................................................................................319 Patterns ...................................................................................................................320 Special Sequence Characters ..............................................................................323 CONTENTS xiii Q Q Q Compiling Regular Expressions .........................................................................323 Matching Strings ...................................................................................................324 Meta Characters ....................................................................................................326 Grouping .................................................................................................................327 System ............................................................................................................................328 Random Number Generation ....................................................................................330 Dates and Times ...........................................................................................................331 Creating a New Time ............................................................................................332 Time Operations ....................................................................................................332 Creating a New Date .............................................................................................333 Date Operations ....................................................................................................333 Time Zone Information ........................................................................................335 Operating System Interface .......................................................................................336 System Information ..............................................................................................336 Process Management ...........................................................................................337 In Conclusion ................................................................................................................341 CHAPTER 12 The GUI — TkInter ...............................................................................343 What Is TkInter? ...........................................................................................................343 Terms and Conditions .................................................................................................343 Event Handling ......................................................................................................344 Callbacks .................................................................................................................344 Widgets ....................................................................................................................345 Layout Managers ...................................................................................................345 Working with TkInter .................................................................................................346 Creating a Label ...........................................................................................................347 Frame Widgets and Centering ..................................................................................349 An Application with a Button ...................................................................................351 Working with Entry Fields and Grid Layouts ........................................................353 Creating a Class to Handle User Interfaces ...........................................................356 Working with List Boxes ............................................................................................358 Scrolling a List Box ................................................................................................361 CONTENTS xiv Q Q Q Menus .............................................................................................................................363 Context Menus .............................................................................................................366 Scale Widgets ................................................................................................................367 RadioButtons and CheckButton ...............................................................................370 Text Widgets .................................................................................................................373 In Conclusion ................................................................................................................375 CHAPTER 13 The Web Server—Apache ...................................................................377 Setting Up Apache .......................................................................................................377 Testing Apache .............................................................................................................378 Your First Python CGI Script: Hello Apache ...........................................................379 Examining the Hello Python Script ...................................................................380 The cgi-bin Directory ............................................................................................381 A Script for Displaying the Environment ...............................................................382 Receiving Data from an HTML File ..........................................................................384 Sending Data to an HTML File ..................................................................................387 How It All Works ...................................................................................................390 Dynamic HTML Displays Based on User Input ......................................................391 HTML Elements ............................................................................................................396 Cookies ...........................................................................................................................399 Uploading Files ............................................................................................................402 Redirection ....................................................................................................................403 Error Handling ..............................................................................................................405 In Conclusion ................................................................................................................406 CHAPTER 14 Working with Databases ...................................................................407 What Is a Database? ...................................................................................................407 Simple Database Terminology ...........................................................................408 What Is MySQL? ...........................................................................................................409 Downloading and Installing ......................................................................................409 Creating a New Database ..........................................................................................410 Creating a New User ....................................................................................................414 CONTENTS xv Q Q Q Opening an Existing Database .................................................................................415 Writing to a Database ................................................................................................417 Reading from a Database ..........................................................................................421 Updating a Database ..................................................................................................424 Deleting from a Database ..........................................................................................427 Searching a Database .................................................................................................430 In Conclusion ................................................................................................................436 CHAPTER 15 Putting It All Together .......................................................................437 Designing the Application .........................................................................................437 Program Flow .........................................................................................................437 User Interface Design ...........................................................................................438 Database Design ...................................................................................................439 Implementing the Database Tables ........................................................................440 Implementing the Forms ...........................................................................................442 Adding Reviews ............................................................................................................449 Adding the Review to the Database ........................................................................452 Listing the Reviews ......................................................................................................456 Deleting Books .............................................................................................................459 In Conclusion ................................................................................................................462 CHAPTER 16 Python and Graphics ..........................................................................463 The PIL Library ..............................................................................................................463 Downloading ..........................................................................................................464 Installing .................................................................................................................464 Verifying Your Installation ..................................................................................465 Creating a New Image ................................................................................................465 Function Parameters ............................................................................................466 Drawing on the Image ................................................................................................467 Drawing the Image ...............................................................................................468 Displaying the Image ...........................................................................................470 CONTENTS xvi Q Q Q
• Table of Contents • Index • Reviews • Reader Reviews • Errata • Academic Python Cookbook, 2nd Edition By David Ascher, Alex Martelli, Anna Ravenscroft Publisher : O'Reilly Pub Date : March 2005 ISBN : 0-596-00797-3 Pages : 844 Copyright Preface The Design of the Book The Implementation of the Book Using the Code from This Book Audience Organization Further Reading Conventions Used in This Book How to Contact Us Safari® Enabled Acknowledgments Chapter 1. Text Introduction Recipe 1.1. Processing a String One Character at a Time Recipe 1.2. Converting Between Characters and Numeric Codes Recipe 1.3. Testing Whether an Object Is String-like Recipe 1.4. Aligning Strings Recipe 1.5. Trimming Space from the Ends of a String Recipe 1.6. Combining Strings Recipe 1.7. Reversing a String by Words or Characters Recipe 1.8. Checking Whether a String Contains a Set of Characters Recipe 1.9. Simplifying Usage of Strings' translate Method Recipe 1.10. Filtering a String for a Set of Characters Recipe 1.11. Checking Whether a String Is Text or Binary Recipe 1.12. Controlling Case Recipe 1.13. Accessing Substrings Recipe 1.14. Changing the Indentation of a Multiline String Recipe 1.15. Expanding and Compressing Tabs Recipe 1.16. Interpolating Variables in a String Recipe 1.17. Interpolating Variables in a Stringin Python 2.4 Recipe 1.18. Replacing Multiple Patterns in a Single Pass Recipe 1.19. Checking a String for Any of Multiple Endings Recipe 1.20. Handling International Text with Unicode Recipe 1.21. Converting Between Unicode and Plain Strings Recipe 1.22. Printing Unicode Charactersto Standard Output
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'aaa.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! import sys, os from PyQt5 import QtCore, QtWidgets, QtGui from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5 import QtCore, QtGui, QtWidgets class U_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(1204, 836) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) MainWindow.setSizePolicy(sizePolicy) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.tableWidget = QtWidgets.QTableWidget(self.centralwidget) self.tableWidget.setGeometry(QtCore.QRect(80, 240, 1041, 371)) self.tableWidget.setAutoScrollMargin(9) self.tableWidget.setRowCount(9) self.tableWidget.setColumnCount(8) self.tableWidget.setObjectName("tableWidget") item = QtWidgets.QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(0, item) item = QtWidgets.QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(1, item) item = QtWidgets.QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(2, item) item = QtWidgets.QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(3, item) item = QtWidgets.QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(4, item) item = QtWidgets.QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(5, item) item = QtWidgets.QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(6, item) item = Q

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值