• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python编程常见问题整理【四】

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

编者按: 本文从stackoverflow收集了Python编程中的常见问题。基于google/baidu/bing翻译将问题议成了中文,希望在英语表达不地道(特别是中英文夹杂)的情况下,也能检索到优质内容入口。     Python相关问题非常多,我们会陆续将这些问题做成专辑,分成多篇文章分别展现。本文是其中的第四篇内容。 注: 点击问题标题直达英文原版网站,点击 加速访问 ,可以通过本站加速器快速访问。


1. 分割字符串与多个分隔符?[Python] (Split Strings with Multiple Delimiters?)

string,split

我想我想做的是一个相当普遍的任务,但我没有找到网上的参考。我有文本,标点符号,我想列表的单词。 “嘿,你 – 你在这里干什么?”应该…

2. 为什么全局变量是邪恶的?[Python] (Why are global variables evil?)

global-variables,side-effects

我试图找到一个好的来源,解释为什么使用全局被认为是在python(和在一般的编程)的坏习惯。有人可以指点我或在这里解释吗?

3. 如何使用Python检查文件是否存在?[Python] (How do I check whether a file exists using Python?)

file,filesystems

如何检查文件是否存在,而不使用try语句?

4. 构建一个基本的Python迭代器[Python] (Build a Basic Python Iterator)

object,iterator

如何在python中创建一个迭代函数(或迭代器对象)?

5. 生成器表达式与列表理解[Python] (Generator Expressions vs. List Comprehension)

list-comprehension,generator

什么时候应该使用生成器表达式和什么时候应该使用列表推导在Python?#生成器表达式(x * 2为范围内的x(256))#列表推导[x * 2 for x in range(256)]

6. 不可变对可变类型[Python] (Immutable vs Mutable types)

immutability,mutable

我对什么是不可变类型感到困惑。我知道float对象被认为是不可变的,这个类型的例子从我的书:类RoundFloat(float):def __new __(cls,val):…

7. 使用Python中的命名空间通过“ElementTree”解析XML[Python] (Parsing XML with namespace in Python via ‘ElementTree’)

xml,xml-parsing,elementtree

我有以下XML,我想使用Python的ElementTree解析:<rdf:RDF xml:base =“http://dbpedia.org/ontology/”xmlns:rdf =“http://www.w3.org/1999 / 02/22-rdf-syntax-ns#“xmlns:…

8. 为什么是python排序我的字典呢? [重复][Python] (Why is python ordering my dictionary like so? [duplicate])

dictionary

这里是字典我havepropertyList = {“id”:“int”,“name”:“char(40)”,“team”:“int”,“realOwner”:“int”,“x”:“int” ,“y”:…

9. 如何在Python中连接到MySQL数据库?[Python] (How do I connect to a MySQL Database in Python?)

mysql

如何使用python程序连接到MySQL数据库?

10. 在Python unicode字符串中删除重音符的最好方法是什么?[Python] (What is the best way to remove accents in a Python unicode string?)

python-3.x,unicode,python-2.x,diacritics

我在Python中有一个Unicode字符串,我想删除所有的口音(diacritics)。我发现在Web上一个优雅的方式来做这个在Java:将Unicode字符串转换为长规范化

11. 使用模块’subprocess’与超时[Python] (Using module ‘subprocess’ with timeout)

multithreading,timeout,subprocess

这里是Python代码运行任意命令返回其stdout数据,或引发非零退出代码的异常:proc = subprocess.Popen(cmd,stderr = subprocess.STDOUT,#Merge …

12. 在Python中使用“global”关键字[Python] (Use of “global” keyword in Python)

global-variables

我从阅读文档中理解的是Python对函数有一个单独的命名空间,如果我想在该函数中使用一个全局变量,我需要使用global.I’m使用Python …

13. 为什么不调用Python字符串方法做任何事情,除非你分配它的输出?[Python] (Why doesn’t calling a Python string method do anything unless you assign its output?)

string,replace

我需要帮助一个简单的字符串替换,但我不知道我做错了。我有这个字符串:hello world我寻找改变你好再见,给我:再见世界我使用这个…

14. Python舍入错误浮点数[duplicate][Python] (Python rounding error with float numbers [duplicate])

python

我不知道这是一个明显的错误,但是当运行一个Python脚本来改变模拟的参数,我意识到delta = 0.29和delta = 0.58的结果丢失。上 …

15. 在Python中给出包含它的列表的项目的索引[Python] (Finding the index of an item given a list containing it in Python)

list

对于列表[“foo”,“bar”,“baz”]和列表“bar”中的项目,在Python中获取其索引(1)的最干净的方法是什么?

16. 从python调用C / C ++?[Python] (Calling C/C++ from python?)

c++c

什么是最快的方式来构造一个python绑定到一个C或C ++库?(使用windows如果这很重要)

17. Python类继承对象[Python] (Python class inherits object)

class,object,inheritance

有没有任何理由类声明继承对象?我只是发现一些代码,这样做,我找不到一个好的理由为什么。class MyClass(object):#class code following …

18. 什么是记忆,我如何在Python中使用它?[Python] (What is memoization and how can I use it in Python?)

memoization

我刚刚开始Python,我不知道什么是memoization和如何使用它。另外,我可以有一个简化的例子吗?

19. 如何在Python 2.7中隐藏子进程的输出[Python] (How to hide output of subprocess in Python 2.7)

python-2.7,subprocess,espeak

我在Ubuntu上使用eSpeak,并有一个Python 2.7脚本,打印并说出一个消息:import subprocesstext =’Hello World.’print textsubprocess.call([‘espeak’,text])eSpeak生成…

20. Python __init__和self他们做什么?[Python] (Python __init__ and self what do they do?)

oop

我在学习Python编程语言,我遇到了一些我不能完全理解的东西。我来自C的背景,但我从来没有走过那么远。我试图…

21. 如何在Python中廉价获取行数?[Python] (How to get line count cheaply in Python?)

text-files,line-count

我需要得到一个大文件(几十万行)在python中的行计数。什么是最有效的方式记忆和时间的方式?现在我做:def file_len(fname):with …

22. 将字节转换为Python字符串[Python] (Convert bytes to a Python string)

string,python-3.x

我使用这个代码从外部程序获得标准输出:>>> from subprocess import * >>> command_stdout = Popen([‘ls’,’-l’],stdout = PIPE).communicate()[0 ] The …

23. 从Python运行shell命令并捕获输出[Python] (Running shell command from Python and capturing the output)

shell,subprocess

我想写一个函数,它将执行一个shell命令并返回其输出作为一个字符串,无论是一个错误或成功消息。我只想得到相同的结果,我会有…

24. 如何打破Python中的多个循环?[Python] (How to break out of multiple loops in Python?)

break,control-flow

给定下面的代码(不工作):while True:#snip:print out current state while True:ok = get_input(“Is this ok?(y / n)”)如果ok ==“y” ==“Y”:break 2#…

25. Python中的@staticmethod和@classmethod之间有什么区别?[Python] (What is the difference between @staticmethod and @classmethod in Python?)

python

用@staticmethod装饰的函数和用@classmethod装饰的函数之间的区别是什么?

26. 使用Python中的for循环在字典上迭代[Python] (Iterating over dictionaries using for loops in Python)

python-2.7,dictionary

我有点困惑的下面的代码:d = {‘x’:1,’y’:2,’z’:3}为键d:打印键,’对应于’,d [不明白是关键部分。 Python如何识别…

27. Python有一个字符串包含子字符串方法吗?[Python] (Does Python have a string contains substring method?)

string,substring,contains

我在Python中寻找一个string.contains或string.indexof方法。我想做:如果不是somestring.contains(“blah”):continue

28. 在Python中读取大文件的懒惰方法?[Python] (Lazy Method for Reading Big File in Python?)

file-io,generator

我有一个非常大的文件4GB,当我尝试读它的计算机挂起。因此我想要读取它一块一块,处理后每个片段存储处理的片段到另一个文件,然后阅读下一个…

29. 为什么Python lambdas有用? [关闭][Python] (Why are Python lambdas useful? [closed])

function,lambda,closures

我试图找出Python lambda。在现实生活中,那些“有趣的”语言项目中的lambda是否应该被遗忘?我敢肯定有一些边缘的情况下,它可能需要,但…

30. 什么是实现嵌套字典的最佳方式?[Python] (What is the best way to implement nested dictionaries?)

data-structures,dictionary,mapping,autovivification

我有一个数据结构,本质上相当于一个嵌套字典。让我们假设它看起来像这样:{‘new jersey’:{‘mercer county’:{‘plumbers’:3,’programmers’…

31. 在Python中,为什么函数可以修改调用者感知的一些参数,而不是其他参数?[Python] (In Python, why can a function modify some arguments as perceived by the caller, but not others?)

python

我是Python的新手,我试图理解它的变量范围的方法。在这个例子中,为什么f()能够改变x的值,如在main()中感知的,而不是n?def f(n,x)的值:…

32. Python中的最大递归深度是多少,如何增加?[Python] (What is the maximum recursion depth in Python, and how to increase it?)

recursion

我有这个尾递归函数:def fib(n,sum):if n <1:return sum else:return fib(n-1,sum + n)c = 998print到n = 997,那么它只是…

33. 在tkinter中交互验证Entry小部件内容[Python] (Interactively validating Entry widget content in tkinter)

validation,textbox,tkinter,entry

什么是推荐的技术交互式验证内容在tkinter条目窗口小部件?我已阅读有关使用validate = True和validatecommand =命令的帖子,看起来这些…

34. ‘b’字符在字符串字面前做什么?[Python] (What does the ‘b’ character do in front of a string literal?)

string,unicode,binary

显然,以下是有效的语法… my_string = b’The字符串’我想知道…这个字符的字符串意味着什么?使用它的什么影响?什么是…

35. 从列表中删除项目时出现奇怪的结果[重复][Python] (strange result when removing item from a list [duplicate])

python

我有这段代码:numbers = range(1,50)for i in numbers:if i <20:print“do something”numbers.remove(i)打印数字,但我得到的结果是:.. 。

36. 有没有简单,优雅的方式来定义单例? [关闭][Python] (Is there a simple, elegant way to define singletons? [closed])

design-patterns,singleton

在Python中定义单例似乎有很多方法。有关于Stack Overflow的共识吗?

37. 如何修复“尝试相对导入非包”即使使用__init__.py[Python] (How to fix “Attempted relative import in non-package” even with __init__.py)

python-import

我试图遵循PEP 328,具有以下目录结构:pkg / __init__.py components / core.py __init__.py tests / core_test.py __init __。pyIn core_test.py我有…

38. 如何读取大文件,在python中逐行[Python] (How to read large file, line by line in python)

python

我想遍历整个文件的每一行。一种方法是读取整个文件,将其保存到列表中,然后查看感兴趣的行。这种方法使用了大量的内存,所以我…

39. 在Python中搜索并替换文件中的一行[Python] (Search and replace a line in a file in Python)

file

我想循环一个文本文件的内容,并在一些行上执行搜索和替换,并将结果写回文件。我可以先加载整个文件在内存中,然后写回来,但…

40. pip:处理多个Python版本?[Python] (pip: dealing with multiple Python versions?)

pip

有什么办法让pip玩得很好的多个版本的Python?例如,我想使用pip明确安装的东西,我的网站2.5安装或我的网站2.6安装….

41. Javascript相当于Python的zip函数[Python] (Javascript equivalent of Python’s zip function)

javascriptfunctional-programming,transpose

是否有JavaScript的等效Python的zip函数?也就是说,给定两个相等长度的数组创建一个对数组。例如,如果我有三个数组,如下所示:var array1 = …

42. Python支持短路吗?[Python] (Does Python support short-circuiting?)

short-circuiting

Python支持布尔表达式中的短路吗?

43. “大数据”工作流使用大熊猫[Python] (“Large data” work flows using pandas)

mongodb,pandas,large-data,hdf5

在学习大熊猫的时候,我已经试图解决这个问题的答案了好几个月了。我使用SAS作为我的日常工作,它是伟大的它的核心支持。然而,SAS是可怕的…

44. @property装饰器如何工作?[Python] (How does the @property decorator work?)

properties,decorator,python-internals

我想了解如何内置的函数属性工作。令我困惑的是,属性也可以作为一个装饰器,但它只接受参数,当用作内置函数和…

45. Python @property与getter和setter[Python] (Python @property versus getters and setters)

properties,getter-setter

这里是一个纯Python特定的设计问题:class MyClass(object):… def get_my_attr(self):… def set_my_attr(self,value):…和class MyClass(object):…

46. Python的迭代器,迭代和迭代协议究竟是什么?[Python] (What exactly are Python’s iterator, iterable, and iteration protocols?)

iterator,iteration

Python中的“iterable”,“iterator”和“iteration”最基本的定义是什么?我读过多个定义,但是它们的确切含义仍然不会沉没。有人请帮助我…

47. 列出字符串/整数的所有排列[Python] (Listing all permutations of a string/integer)

c#algorithm,f#,permutation

编程访谈中的一个常见任务(而不是我的面试经验)是一个字符串或整数,并列出每一个可能的排列。有一个例子,如何做到这一点…

48. 使用python的多处理池时不能pickle Pool.map()[Python] (Can’t pickle when using python’s multiprocessing Pool.map())

multithreading,multiprocessing,pickle,pool

我试图使用多处理的Pool.map()函数同时划分工作。当我使用下面的代码,它工作正常:import multiprocessingdef f(x):return x * xdef go():…

49. 在Windows 7上添加Python路径[Python] (Adding Python Path on Windows 7)

windows,python-2.7,path

我一直在尝试添加Python路径到Windows 7的命令行,但无论我尝试的方法,似乎没有什么工作。我使用set命令,我已经尝试通过编辑添加…

50. 在tkinter的两个帧之间切换[Python] (Switch between two frames in tkinter)

python-3.x,tkinter,frame

我已经建立了我的前几个脚本与一个漂亮的小GUI,正如教程向我展示的,但没有一个解决了一个更复杂的程序做什么。如果你有一个’开始…


鲜花

握手

雷人

路过

鸡蛋
专题导读
上一篇:
Python编程常见问题整理【三】发布时间:2022-05-14
下一篇:
Scala编程常见问题整理【二】发布时间:2022-05-14
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap