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

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

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

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


1. input()error – NameError:name’…’未定义[Python] (input() error – NameError: name ‘…’ is not defined)

python-2.7,python-3.x,input,nameerror

我得到一个错误,当我尝试运行这个简单的python脚本:input_variable = input(“输入您的名称:”)print(“您的名字是”+ input_variable)让我说我输入“dude”,我的错误。 … ..

2. 如何查看脚本?[Python] (How can you profile a script?)

performance,profiling,time-complexity

欧拉项目和其他编码比赛通常有最大的运行时间或人们吹嘘他们的特定解决方案运行的速度。有了python,有时方法有点kludgey – 即…

3. 如何强制分割为浮点?除法舍入为0[Python] (How can I force division to be floating point? Division keeps rounding down to 0)

floating-point,integer,division,python-2.x

我有两个整数值a和b,但我需要它们的浮点比率。我知道a <b,我想计算a / b,所以如果我使用整数除法,我总是得到0与剩余的a.How …

4. * args和** kwargs? [重复][Python] (*args and **kwargs? [duplicate])

args,kwargs

所以我有困难的概念* args和** kwargs.So远我了解到:* args =参数列表 – 位置参数** kwargs =字典 – 其键成为单独的关键字…

5. 如何导入给定完整路径的模块?[Python] (How to import a module given the full path?)

configuration,python-import,python-module

给定它的完整路径,我如何加载一个Python模块?请注意,该文件可以在文件系统中的任何位置,因为它是一个配置选项。

6. Python,Unicode和Windows控制台[Python] (Python, Unicode, and the Windows console)

unicode

当我尝试在Windows控制台打印Unicode字符串,我得到一个UnicodeEncodeError:’charmap’编解码器不能编码字符….错误。我假设这是因为Windows控制台不接受…

7. 如何在Python中生成列表的所有排列[Python] (How to generate all permutations of a list in Python)

algorithm,permutation,combinatorics,python-2.5

例如:permutations([])[] permutations([1])[1] permutations([1,2]),如何在Python中生成列表的所有排列, [1,2] …

8. Python中的局部变量嵌套函数[Python] (Local variables in Python nested functions)

scope,nested-function

好吧,忍受我在这,我知道它会看起来可怕的复杂,但请帮助我明白发生了什么。从functools import partialclass Cage(object):def __init __(self,…

9. 为什么Button参数“command”被声明时执行?[Python] (Why is Button parameter “commandâ€� executed when declared?)

tkinter

我的代码是:from Tkinter import * admin = Tk()def button(an):print a print’het’b = Button(admin,text =’as’,command = button(’hey’))b.pack )mainloop()按钮不工作,它…

10. 使用__init __()方法了解Python super()[duplicate][Python] (Understanding Python super() with __init__() methods [duplicate])

inheritance,super

我试图理解super()。从它的外观,两个子类可以创建只是罚款。我很好奇,下面的子类之间有什么区别:class …

11. Python变量范围错误[Python] (Python variable scope error)

variables,scope

我已经编程了很多年,最近开始学习Python。下面的代码在python 2.5和3.0(在OS X上,如果重要的话)的工作原理如下:a,b,c =(1,2,3)print(a,b,…

12. 获取一系列列表的笛卡尔乘积?[Python] (Get the cartesian product of a series of lists?)

list

如何从一组列表中获取笛卡尔乘积(每个可能的值组合)?输入:somelists = [[1,2,3],[‘a’,’b’],[4,5]输出:[(1,’a’,4),(1,…

13. Python列表解析地图[Python] (Python List Comprehension Vs. Map)

list-comprehension,map-function

有理由更喜欢使用map()超过列表推导,反之亦然吗?是一个一般更有效或一般认为比另一个更加pythonic?

14. 如何通过while循环动态创建变量? [重复][Python] (How can you dynamically create variables via a while loop? [duplicate])

variables

我想通过一个while循环在Python中动态创建变量。任何人都有任何创造性的方法这样做?

15. 如何在单个表达式中合并两个Python字典?[Python] (How to merge two Python dictionaries in a single expression?)

dictionary,mapping,expression,idioms

我有两个Python字典,我想写一个单一的表达式,返回这两个字典,合并。 update()方法将是我需要的,如果它返回的结果,而不是…

16. 我如何在Python中表示一个“枚举”?[Python] (How can I represent an ‘Enum’ in Python?)

python-3.x,enums

我主要是一个C#开发人员,但我目前正在一个项目的Python。我如何表示相当于一个Enum在Python?

17. Python从用户读取单个字符[Python] (Python read a single character from the user)

input

有没有从用户输入中读取一个单一字符的方法?例如,他们在终端按一个键,并返回(类似于getch())。我知道在Windows中有一个功能…

18. 如何提高这段代码的性能?[Python] (How to improve performance of this code?)

performance,optimization,time-complexity

感谢在这里的人的一些帮助,我能够得到我的代码为塔斯马尼亚骆驼拼图工作。但是,它是可怕的慢(我想,我不知道,因为这是我的第一个程序在python)。 … …

19. 如何终止使用shell = True启动的python子进程[Python] (How to terminate a python subprocess launched with shell=True)

linux,subprocess,kill-process

我使用以下命令启动一个子进程:p = subprocess.Popen(cmd,stdout = subprocess.PIPE,shell = True)但是,当我尝试杀死使用:p.terminate()或p.kill命令…

20. 如何在Python中解析XML?[Python] (How do I parse XML in Python?)

xml

我在一个包含xml的数据库中有很多行,我试图写一个Python脚本,将通过这些行,并计数一个特定的节点属性的实例数量显示。用于…

21. 如何附加到文件?[Python] (How do you append to a file?)

file,append

如何附加到文件而不是覆盖它?有没有一个特殊的功能附加到文件?

22. Python:从subprocess.communicate()读取流输入[Python] (Python: read streaming input from subprocess.communicate())

subprocess

我使用Python的subprocess.communicate()从运行大约一分钟的进程中读取stdout。如何以流的方式打印出该进程的stdout的每一行,以便我可以…

23. 在Python中没有[]的列表推导[Python] (List comprehension without [ ] in Python)

list-comprehension

加入列表:>>>”.join([str(_)for _ in xrange(10)])’0123456789’join必须使用iterable.apparently,join的参数是[str(_)for _ in xrange 10)],它是一个列表…

24. Python字符串格式化:%vs. .format[Python] (Python string formatting: % vs. .format)

performance,logging,string-formatting

Python 2.6引入了与现有的%运算符略有不同的语法的str.format()方法。哪个更好,为什么情况?以下使用每种方法,具有相同的…

25. Python中的UnboundLocalError [duplicate][Python] (UnboundLocalError in Python [duplicate])

global-variables,scope

我在这里做错了?counter = 0def increment():counter + = 1increment()上面的代码引发UnboundLocalError。

26. 如何打印没有换行符或空格?[Python] (How to print without newline or space?)

newline

问题是在标题中。我喜欢在python中做我在这个例子中在c:#include <stdio.h> int main(){int i; for(i = 0; i <10; i ++)printf(“。”); return 0;} …

27. 在Python中`==`和`is`之间有区别吗?[Python] (Is there a difference between `==` and `is` in Python?)

reference,semantics

我的Google-fu已经失败了在Python中,以下两个测试等于相等(ha!)?n = 5#测试one.if n == 5:print’Yay!’#测试two.if n是5 :print’Yay!’这是…

28. 如何做相对导入Python?[Python] (How to do relative imports in Python?)

python-import,python-module

想象这个目录结构:app / __init__.py sub1 / __init__.py mod1.py sub2 / __init__.py mod2.pyI’m编码mod1,我需要从mod2导入一些东西。怎么样 …

29. Python字典,如何保持键/值在相同的顺序声明?[Python] (Python dictionary, how to keep keys/values in same order as declared?)

dictionary,order

新的Python和有关于字典的问题。我有一个字典,我宣布在一个特定的顺序,并希望保持它的顺序,所有的时间。键/值不能真正保存在…

30. “u”和“r”字符串标志在Python中究竟做什么,什么是原始字符串字面量?[Python] (What exactly do “u” and “r” string flags do in Python, and what are raw string literals?)

unicode,rawstring

在提出这个问题时,我意识到我不太了解原始字符串。对于有人声称是一个Django培训师,这吸吮我知道什么是编码,我知道什么u单独做,因为我…

31. 如何通过键排序字典?[Python] (How can I sort a dictionary by key?)

sorting,dictionary

从{2:3,1:89,4:5,3:0}到{1:89,2:3,3:0,4:5}会是什么好的方法?它们都使用返回元组的“sorted”运算符。

32. 我如何在Python中并行地遍历两个列表?[Python] (How can I iterate through two lists in parallel in Python?)

iterator

我在Python中有两个iterable,我想成对地讨论它们:foo =(1,2,3)bar =(4,5,6)for(f,b)在some_iterator “f:”,f“”; b:“,bIt应该导致:f:1; …

33. 在Python中将datetime.date转换为UTC时间戳[Python] (Converting datetime.date to UTC timestamp in Python)

datetime,utc

我正在处理Python中的日期,我需要将它们转换为UTC时间戳在Javascript中使用。以下代码不工作:>>> d = datetime.date(2011,01,01)>>> …

34. 在Python中将列表的字符串表示转换为列表[Python] (Convert string representation of list to list in Python)

string

我想知道最简单的方法是将一个字符串列表如下所示转换为列表:x = u'[“A”,“B”,“C”,“D”]’逗号和空格里面…

35. 循环“忘记”删除一些项目[duplicate][Python] (Loop “Forgets” to Remove Some Items [duplicate])

string,list

在这段代码中,我试图创建一个函数anti_vowel,将从字符串中删除所有元音(aeiouAEOU)。我认为它应该工作确定,但当我运行它,示例文本“嘿看字!是…

36. 如何将文件逐行读入列表?[Python] (How to read a file line-by-line into a list?)

string,file,readlines

如何读取Python中的每一行文件,并将每行存储为列表中的元素?我想逐行读取文件,每行都附加到列表的末尾。

37. 在Python中switch语句的替换?[Python] (Replacements for switch statement in Python?)

switch-statement

我想在Python中编写一个函数,它根据输入索引的值返回不同的固定值。在其他语言中,我会使用switch或case语句,但Python不会出现…

38. (lambda)函数闭包在Python中捕获什么?[Python] (What do (lambda) function closures capture in Python?)

lambda,closures

最近我开始使用Python玩,我发现了闭包工作方式奇特的东西。考虑下面的代码:adders = [0,1,2,3] for i in [0,1,2,3]:adders [i] = lambda a:…

39. 如何保护Python代码?[Python] (How do I protect Python code?)

licensing,obfuscation,copy-protection

我正在开发一个Python软件,将分发给我的雇主的客户。我的雇主想限制软件的使用时间限制许可证文件。如果我们…

40. python3.x中的raw_input()和input()有什么区别?[Python] (What’s the difference between raw_input() and input() in python3.x?)

python-3.x

python3.x中的raw_input()和input()有什么区别?

41. 如何计算列表项在Python中的出现次数?[Python] (How can I count the occurrences of a list item in Python?)

list,count

给定一个项目,我如何计算它在Python列表中的出现次数?

42. 如何刷新Python的输出输出?[Python] (How to flush output of Python print?)

printing,flush

如何强制Python的打印功能输出到屏幕?这不是禁用输出缓冲的重复 – 链接的问题是尝试无缓冲输出,而这是更通用的。 … …

43. 在Python中使用函数的名称从字符串调用模块的函数[Python] (Calling a function of a module from a string with the function’s name in Python)

python

在Python程序中,使用函数的名字给出一个字符串,最好的方法是调用一个函数。例如,假设我有一个模块foo,我有一个字符串,其内容…

44. 使用Python在终端中打印颜色?[Python] (Print in terminal with colors using Python?)

unicode,terminal,ansi-colors

如何在Python中输出彩色文本到终端?什么是最好的Unicode符号来表示实体块?

45. 在Python中从字符串中剥离标点符号的最佳方法[Python] (Best way to strip punctuation from a string in Python)

string,punctuation

看来像应该有一个更简单的方法:import strings =“string。With。Punctuation? #Sample string out = s.translate(string.maketrans(“”,“”),string.punctuation)有吗?

46. 从脚本导入安装的软件包引发“AttributeError:模块没有属性”或“ImportError:无法导入名称”[Python] (Importing installed package from script raises “AttributeError: module has no attribute” or “ImportError: cannot import name”)

exception,python-module,shadowing

我有一个脚本命名requests.py,导入请求包。脚本无法从包中访问属性,也无法导入它们。为什么这不工作,如何解决它?

47. 如何列出目录的所有文件?[Python] (How to list all files of a directory?)

directory

如何列出python中目录的所有文件并将它们添加到列表中?

48. 从相对路径导入模块[Python] (Import a module from a relative path)

relative-path,python-import

我如何导入一个python模块给定它的相对路径?例如,如果dirFoo包含Foo.py和dirBar,并且dirBar包含Bar.py,我如何导入Bar.py到Foo.py?的视觉…

49. 在Python中将stdout重定向到文件?[Python] (Redirect stdout to a file in Python?)

stdout

如何在Python中将stdout重定向到一个任意文件?当一个长时间运行的Python脚本(例如Web应用程序)从ssh会话中启动,并且被关闭,并且ssh会话关闭时,…

50. Python的re.search和re.match有什么区别?[Python] (What is the difference between Python’s re.search and re.match?)

regex,search,match

在Python re模块中的search()和match()函数有什么区别?我已经阅读了文档(当前文档),但我似乎从来不记得它。我不得不看看…


鲜花

握手

雷人

路过

鸡蛋
专题导读
上一篇:
Python编程常见问题整理【一】发布时间:2022-05-14
下一篇:
揭开机器学习的面纱:SVM 100行代码实现[Python版]发布时间: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