How do I check if a list is empty?

For example, if passed the following: a = [] How do I check to see if a is empty? if not a: print("List is empty") 使用空列表的隐式布尔型是相当pythonic。 The pythonic way to do it is from the PEP 8 style guide (where Yes means “recommended” and No means “not recommended”): For sequences, (strings, lists, tuples), use the fact that empty sequences are false. Yes: if not seq: if seq:

如何检查列表是否为空?

例如,如果通过以下内容: a = [] 如何检查a是否为空? if not a: print("List is empty") 使用空列表的隐式布尔型是相当pythonic。 Pythonic的方式是从PEP 8风格指南(其中Yes表示“推荐”, No表示“不推荐”): 对于序列(字符串,列表,元组),请使用空序列为假的事实。 Yes: if not seq: if seq: No: if len(seq): if not len(seq): 我明确喜欢它: if len(li) == 0: print('the list is empty')

How do I pass a variable by reference?

The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original' class PassByReference: def __init__(self): self.variable = 'Original' self.change(self.variable) print(self.variable) def change(self, var): var = 'Changed' Is there something I can do to

如何通过引用传递变量?

Python文档似乎不清楚参数是按引用还是按值传递,并且以下代码会生成未更改的值“原始” class PassByReference: def __init__(self): self.variable = 'Original' self.change(self.variable) print(self.variable) def change(self, var): var = 'Changed' 有什么我可以做的,通过实际参考传递变量? 参数通过赋值传递。 这背后的理由是双重的: 传入的参数实际上是一个对象的

How do I list all files of a directory?

我如何在Python中列出目录中的所有文件并将它们添加到list ? os.listdir() will get you everything that's in a directory - files and directories. If you want just files, you could either filter this down using os.path : from os import listdir from os.path import isfile, join onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] or you could use os.walk() which will yield two lis

如何列出目录的所有文件?

我如何在Python中列出目录中的所有文件并将它们添加到list ? os.listdir()会为你提供目录中的所有内容 - 文件和目录。 如果你只需要文件,你可以使用os.path过滤掉它: from os import listdir from os.path import isfile, join onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] 或者你可以使用os.walk() ,它将为它访问的每个目录产生两个列表 - 为你分割成文件和目录。 如果你只想要最上面的目录

How do I sort a dictionary by value?

I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question How do I sort a list of dictionaries by values of the dictionary in Python? and probably could change my code to have a

如何按价值对字典进行排序?

我有一个从数据库中的两个字段中读取值的字典:一个字符串字段和一个数字字段。 字符串字段是唯一的,所以这是字典的关键。 我可以对键进行排序,但是如何根据这些值进行排序? 注意:我已阅读Stack Overflow问题如何按Python中字典的值对字典列表进行排序? 并可能可以改变我的代码有一个字典的列表,但因为我真的不需要一个字典的列表,我想知道是否有一个更简单的解决方案。 对字典进行排序是不可能的,只能得到已排

How to merge two dictionaries in a single expression?

I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The update() method would be what I need, if it returned its result instead of modifying a dict in-place. >>> x = {'a':1, 'b': 2} >>> y = {'b':10, 'c': 11} >>> z = x.update(y) >>> print(z) None >>> x {'a': 1, 'b': 10, 'c': 11} How can

如何在单个表达式中合并两个字典?

我有两个Python字典,我想写一个表达式来返回这两个字典,合并。 update()方法是我需要的,如果它返回结果而不是就地修改字典。 >>> x = {'a':1, 'b': 2} >>> y = {'b':10, 'c': 11} >>> z = x.update(y) >>> print(z) None >>> x {'a': 1, 'b': 10, 'c': 11} 我怎样才能得到最终的合并字典在z ,而不是x ? (为了更加清楚, dict.update()的最后一次冲突处理也是我正在寻找

Calling an external command in Python

我如何从Python脚本中调用一个外部命令(就像我在Unix shell或Windows命令提示符下键入的那样)? Look at the subprocess module in the standard library: from subprocess import call call(["ls", "-l"]) The advantage of subprocess vs system is that it is more flexible (you can get the stdout, stderr, the "real" status code, better error handling, etc...). The official docs recommend the subp

在Python中调用外部命令

我如何从Python脚本中调用一个外部命令(就像我在Unix shell或Windows命令提示符下键入的那样)? 查看标准库中的子进程模块: from subprocess import call call(["ls", "-l"]) 子进程 vs 系统的优点是它更加灵活(你可以得到stdout,stderr,“真实”状态码,更好的错误处理等等)。 官方文档通过替代os.system()推荐子流程模块: 子流程模块提供了更强大的功能,用于产生新流程并检索其结果; 使用该模块优于使用此函数

Error in use of python multiprocessing module with generator function.

Could some one explain what is wrong with below code from multiprocessing import Pool def sq(x): yield x**2 p = Pool(2) n = p.map(sq, range(10)) I am getting following error MaybeEncodingError Traceback (most recent call last) in () 5 p = Pool(2) 6 ----> 7 n = p.map(sq, range(10)) /home/devil/anaconda3/lib/python3.4/multiprocessing/pool.py in map(self, func, iterable, chunksize) 258

带有生成器函数的python多处理模块的使用出错。

有人可以解释下面的代码有什么问题 from multiprocessing import Pool def sq(x): yield x**2 p = Pool(2) n = p.map(sq, range(10)) 我得到以下错误 ()中的MaybeEncodingError Traceback(最近一次调用最后一次)p = Pool(2)6 ----> 7 n = p.map(sq,range(10)) /home/devil/anaconda3/lib/python3.4/multiprocessing/pool.py在映射(self,func,iterable,chunksize)258中返回的列表中。 259'

Does Python have a string 'contains' substring method?

I'm looking for a string.contains or string.indexof method in Python. I want to do: if not somestring.contains("blah"): continue 您可以使用in运算符: if "blah" not in somestring: continue If it's just a substring search you can use string.find("substring") . You do have to be a little careful with find , index , and in though, as they are substring searches. In ot

Python是否有一个字符串'contains'substring方法?

我正在Python中寻找一个string.contains或string.indexof方法。 我想要做: if not somestring.contains("blah"): continue 您可以使用in运算符: if "blah" not in somestring: continue 如果它只是一个子字符串搜索,你可以使用string.find("substring") 。 你必须与小心一点find , index ,并in虽然,因为它们是字符串搜索。 换句话说,这个: s = "This be a string" if s.find("is") == -1:

What does if

if __name__ == "__main__":做什么? # Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while True: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == "__main__": lock = thread.allocate_lock() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.star

怎么做

if __name__ == "__main__":做什么? # Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while True: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == "__main__": lock = thread.allocate_lock() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.star

How can I create a directory if it does not exist?

What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried: import os file_path = "/my/directory/filename.txt" directory = os.path.dirname(file_path) try: os.stat(directory) except: os.mkdir(directory) f = file(filename) Somehow, I missed os.path.exists (thanks kanja, Blai

如何创建一个不存在的目录?

检查文件将要写入的目录是否存在最优雅的方法是什么,如果不是,使用Python创建目录? 这是我试过的: import os file_path = "/my/directory/filename.txt" directory = os.path.dirname(file_path) try: os.stat(directory) except: os.mkdir(directory) f = file(filename) 不知何故,我错过了os.path.exists (感谢kanja,Blair和Douglas)。 这是我现在拥有的: def ensure_dir(file_path): dire