Home Backend Development Python Tutorial Python易忽视知识点小结

Python易忽视知识点小结

Jun 06, 2016 am 11:17 AM
python Knowledge points

这里记录Python中容易被忽视的小问题

一、input(...)和raw_input(...)

#简单的差看帮助文档input(...)和raw_input(...)有如下区别 
>>> help(input) 
Help on built-in function input in module __builtin__: 
input(...) 
  input([prompt]) -> value 
  Equivalent to eval(raw_input(prompt)). 
>>> help(raw_input) 
Help on built-in function raw_input in module __builtin__: 
raw_input(...) 
  raw_input([prompt]) -> string 
    
  Read a string from standard input. The trailing newline is stripped. 
  If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. 
  On Unix, GNU readline is used if enabled. The prompt string, if given, 
  is printed without a trailing newline before reading. 
  
#可见 input会根据输入的内容eval结果来返回值,即输入纯数字,则得到的就是纯数字 
#     raw_input返回的才是字符串 
#test: 
>>> a = input("输入数字") 
输入数字1 
>>> type(a) 
<type 'int'> 
>>> b=raw_input("输入数字") 
输入数字1 
>>> type(b) 
<type 'str'> 

Copy after login

ps:在python3.0以后的版本中,raw_input和input合体了,取消raw_input,并用input代替,所以现在的版本input接收的是字符串

二、python三目运算符

虽然Python没有C++的三目运算符(?:),但也有类似的替代方案,

那就是
1、 true_part if condition else false_part

>>> 1 if True else 0 
1 
>>> 1 if False else 0 
0 
>>> "True" if True else "False" 
'True' 
>>> "True" if True else "False" 
'Falser' 

Copy after login

2、 (condition and [true_part] or [false_part] )[0]

>>> (True and ["True"] or ["False"])[0] 
'True' 
>>> (False and ["True"] or ["False"])[0] 
'False' 
>>>  

Copy after login

三、获得指定字符串在整个字符串中出现第N次的索引

# -*- coding: cp936 -*- 
def findStr(string, subStr, findCnt): 
  listStr = a.split(subStr,findCnt) 
  if len(listStr) <= findCnt: 
    return -1 
  return len(string)-len(listStr[-1])-len(subStr) 
#test 
a = "12345(1)254354(1)3534(1)14" 
sub = "(1)" 
N = 2   #查找第2次出现的位置 
print findStr(a,sub,N) 
N = 10   #查找第10次出现的位置 
print findStr(a,sub,N) 
#结果 
#>>>  
#14 
#-1 

Copy after login

四、enumerate用法:

遍历序列的时候,可能同时需要用到序列的索引和对应的值,这时候可以采用enumerate方法进行遍历

enumerate的说明如下:

>>> help(enumerate) 
Help on class enumerate in module __builtin__: 
 
class enumerate(object) 
 | enumerate(iterable[, start]) -> iterator for index, value of iterable 
 |  
 | Return an enumerate object. iterable must be another object that supports 
 | iteration. The enumerate object yields pairs containing a count (from 
 | start, which defaults to zero) and a value yielded by the iterable argument. 
 | enumerate is useful for obtaining an indexed list: 
 |   (0, seq[0]), (1, seq[1]), (2, seq[2]), ... 
 |  
 | Methods defined here: 
 |  
 | __getattribute__(...) 
 |   x.__getattribute__('name') <==> x.name 
 |  
 | __iter__(...) 
 |   x.__iter__() <==> iter(x) 
 |  
 | next(...) 
 |   x.next() -> the next value, or raise StopIteration 
 |  
 | ----------------------------------------------------------------------
 | Data and other attributes defined here: 
 |  
 | __new__ = <built-in method __new__ of type object> 
 |   T.__new__(S, ...) -> a new object with type S, a subtype of T 

Copy after login

五、遍历序列的方法

>>> List = ['a','b','c'] 
>>> for index, value in enumerate(List): 
  print index, value 
0 a 
1 b 
2 c 
>>>  

Copy after login

六、使用python random模块的sample函数从列表中随机选择一组元素

import 
List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  
slice = random.sample(List, 5)
#从List中随机获取5个元素,作为一个片断返回  
print slice  
print List #原有序列并没有改变。
Copy after login

七、用json打印包含中文的列表字典等

# -*- coding:utf-8 -*- 
import json 
#你的列表 
listA = [{'path': ['[AWS] \xe7\xbe\x8e\xe5\xb0\x91\xe5\xa5\xb3\xe6\x88\x98\xe5\xa3\xab Sailor Moon Crystal - Moon Pride MV[BIG5][BDrip 1080p x264 AAC][6E5CFE86].mp4'], 'length': 131248608L}, {'path': ['[AWS] \xe7\xbe\x8e\xe5\xb0\x91\xe5\xa5\xb3\xe6\x88\x98\xe5\xa3\xab Sailor Moon Crystal - Moon Pride MV[BIG5][BDrip 720p x264 AAC][639D304A].mp4'], 'length': 103166306L}, {'path': ['[AWS] \xe7\xbe\x8e\xe5\xb0\x91\xe5\xa5\xb3\xe6\x88\x98\xe5\xa3\xab Sailor Moon Crystal - Moon Pride MV[BIG5][BDrip 480p x264 AAC][5A81BACA].mp4'], 'length': 75198408L}]
#打印列表
print json.dumps(listA, encoding='UTF-8', ensure_ascii=False) 

Copy after login

输出结果:

>>>  
[{"path": ["[AWS] 美少女战士 Sailor Moon Crystal - Moon Pride MV[BIG5][BDrip 1080p x264 AAC][6E5CFE86].mp4"], "length": 131248608}, {"path": ["[AWS] 美少女战士 Sailor Moon Crystal - Moon Pride MV[BIG5][BDrip 720p x264 AAC][639D304A].mp4"], "length": 103166306}, {"path": ["[AWS] 美少女战士 Sailor Moon Crystal - Moon Pride MV[BIG5][BDrip 480p x264 AAC][5A81BACA].mp4"], "length": 75198408}] 

Copy after login

希望本文所述对大家的Python程序设计有所帮助。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

Can vscode run ipynb Can vscode run ipynb Apr 15, 2025 pm 07:30 PM

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.

See all articles