編者按: 本文從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,正如教程向我展示的,但沒有一個解決了一個更複雜的程序做什麽。如果你有一個’開始…