精华内容
下载资源
问答
  • python中创建空列表If you want to learn how to create an empty list in Python ... 如果您想学习如何在Python中高效地创建一个空列表,那么本文适合您。 You will learn: 您将学习: How to create an empty li...

    python中创建空列表

    If you want to learn how to create an empty list in Python efficiently, then this article is for you.

    如果您想学习如何在Python中高效地创建一个空列表,那么本文适合您。

    You will learn:

    您将学习:

    • How to create an empty list using square brackets [].

      如何使用方括号[]创建一个空列表。

    • How to create an empty list using list().

      如何使用list()创建一个空列表。

    • Their use cases.

      他们的用例。
    • How efficient they are (one is faster than the other!). We will use the timeit module to compare them.

      它们的效率(一个比另一个快!)。 我们将使用timeit模块进行比较。

    Let's begin! 🔅

    让我们开始! 🔅

    🔹使用方括号 (🔹 Using Square Brackets)

    You can create an empty list with an empty pair of square brackets, like this:  

    您可以使用一对空的方括号创建一个空列表,如下所示:

    💡 Tip: We assign the empty list to a variable to use it later in our program.

    提示:我们将空列表分配给变量,以便稍后在程序中使用它。

    For example:

    例如:

    num = []

    The empty list will have length 0, as you can see right here:

    空列表的长度为0 ,您可以在此处看到:

    >>> num = []
    >>> len(num)
    0

    Empty lists are falsy values, which means that they evaluate to False in a boolean context:

    空列表是虚假的值,这意味着它们在布尔上下文中的计算结果为False

    >>> num = []
    >>> bool(num)
    False

    将元素添加到空列表 (Add Elements to an Empty List)

    You can add elements to an empty list using the methods append() and insert():

    您可以使用方法append()insert()将元素添加到空列表中:

    • append() adds the element to the end of the list.

      append()将元素添加到列表的末尾。

    • insert() adds the element at the particular index of the list that you choose.

      insert()将元素添加到您选择的列表的特定索引处。

    Since lists can be either truthy or falsy values depending on whether they are empty or not when they are evaluated, you can use them in conditionals like this:

    由于列表可以是真实值或虚假值,具体取决于它们在求值时是否为空,因此可以在如下条件中使用它们:

    if num:
    	print("This list is not empty")
    else:
    	print("This list is empty")

    The output of this code is:

    此代码的输出是:

    This list is empty

    Because the list was empty, so it evaluates to False.

    由于列表为空,因此其值为False。

    In general:

    一般来说:

    • If the list is not empty, it evaluates to True, so the if clause is executed.

      如果列表不为空,则计算结果为True ,因此将执行if子句。

    • If the list is empty, it evaluates to False, so the else clause is executed.

      如果列表为空,则结果为False ,因此执行else子句。

    例: (Example:)

    In the example below, we create an empty list and assign it to the variable num. Then, using a for loop, we add a sequence of elements (integers) to the list that was initially empty:

    在下面的示例中,我们创建一个空列表并将其分配给变量num 。 然后,使用for循环,将一系列元素(整数)添加到最初为空的列表中:

    >>> num = []
    >>> for i in range(3, 15, 2):
    	num.append(i)

    We check the value of the variable to see if the items were appended successfully and confirm that the list is not empty anymore:  

    我们检查变量的值以查看是否成功添加了项目,并确认列表不再为空:

    >>> num
    [3, 5, 7, 9, 11, 13]

    💡 Tip: We commonly use append() to add the first element to an empty list, but you can also add this element calling the insert() method with index 0:

    提示:我们通常使用append()将第一个元素添加到空列表中,但是您也可以使用索引0调用insert()方法添加此元素:

    >>> num = []
    >>> num.insert(0, 1.5) # add the float 1.5 at index 0
    >>> num
    [1.5]

    🔸使用list()构造函数 (🔸 Using the list() Constructor)

    Alternatively, you can create an empty list with the type constructor list(), which creates a new list object.

    另外,您可以使用构造函数list()创建一个空列表,这将创建一个新的列表对象。

    According to the Python Documentation:

    根据Python文档

    If no argument is given, the constructor creates a new empty list, [].

    如果未提供任何参数,则构造函数将创建一个新的空列表[]

    💡 Tip: This creates a new list object in memory and since we didn't pass any arguments to list(), an empty list will be created.

    提示:这将在内存中创建一个新的列表对象,由于我们没有将任何参数传递给list() ,因此将创建一个空列表。

    For example:

    例如:

    num = list()

    This empty list will have length 0, as you can see right here:

    空列表的长度为0 ,您可以在此处看到:

    >>> num = list()
    >>> len(num)
    0

    And it is a falsy value when it is empty (it evaluates to False in a boolean context):

    当它为空时,它是一个伪造的值(在布尔上下文中其值为False ):

    >>> num = list()
    >>> bool(num)
    False

    例: (Example:)

    This is a fully functional list, so we can add elements to it:

    这是一个功能齐全的列表,因此我们可以向其中添加元素:

    >>> num = list()
    >>> for i in range(3, 15, 2):
    	num.append(i)

    And the result will be a non-empty list, as you can see right here:

    结果将是一个非空列表,如您在此处看到的那样:

    >>> num
    [3, 5, 7, 9, 11, 13]

    🔹用例 (🔹 Use Cases)

    • We typically use list() to create lists from existing iterables such as strings, dictionaries, or tuples.

      我们通常使用list()从现有可迭代对象(如字符串,字典或元组list()创建列表。

    • You will commonly see square brackets [] being used to create empty lists in Python because this syntax is more concise and faster.

      您通常会看到方括号[]用于在Python中创建空列表,因为此语法更简洁,更快捷。

    🔸效率 (🔸 Efficiency)

    Wait! I just told you that [] is faster than list()...

    等待! 我只是告诉你[]list()更快...

    But how much faster?

    但是要快多少?

    Let's check their time efficiencies using the timeit module.

    让我们使用timeit模块检查它们的时间效率。

    To use this module in your Python program, you need to import it:

    要在您的Python程序中使用此模块,您需要将其导入:

    >>> import timeit

    Specifically, we will use the timeit function from this module, which you can call with this syntax:

    具体来说,我们将使用此模块中的timeit函数 ,您可以使用以下语法进行调用:

    💡 Tip: The code is repeated several times to reduce time differences that may arise from external factors such as other processes that might be running at that particular moment. This makes the results more reliable for comparison purposes.

    💡 提示:该代码重复了几次,以减少由外部因素(例如,可能在该特定时刻运行的其他进程)引起的时间差异。 这使得结果更加可靠,可用于比较。

    🚩 On your marks... get set... ready! Here is the code and output:

    marks 在您的标记上...准备好...准备好了! 这是代码和输出:

    First, we import the module.

    首先,我们导入模块。

    >>> import timeit

    Then, we start testing each syntax.

    然后,我们开始测试每种语法。

    测试[](Testing []:)

    >>> timeit.timeit('[]', number=10**4)
    0.0008467000000109692

    测试list()(Testing list():)

    >>> timeit.timeit('list()', number=10**4)
    0.002867799999989984

    💡 Tip: Notice that the code that you want to time has to be surrounded by single quotes '' or double quotes "". The time returned by the timeit function is expressed in seconds.

    提示:请注意,要计时的代码必须用单引号''或双引号""包围。 timeit函数返回的时间以秒为单位。

    Compare these results:

    比较这些结果:

    • []: 0.0008467000000109692

      []0.0008467000000109692

    • list(): 0.002867799999989984

      list()0.002867799999989984

    You can see that [] is much faster than list(). There was a difference of approximately 0.002 seconds in this test:

    您可以看到[]list()快得多。 此测试相差约0.002秒:

    >>> 0.002867799999989984 - 0.0008467000000109692
    0.0020210999999790147

    I'm sure that you must be asking this right now: Why is list() less efficient than [] if they do exactly the same thing?

    我敢肯定,您现在必须问这个问题:如果list()做的完全一样,为什么它们的效率比[]低?

    Well... list() is slower because it requires looking up the name of the function, calling it, and then creating the list object in memory. In contrast, [] is like a "shortcut" that doesn't require so many intermediate steps to create the list in memory.

    好吧... list()较慢,因为它需要查找函数名称,调用它,然后在内存中创建列表对象。 相反, []就像一个“快捷方式”,不需要太多的中间步骤即可在内存中创建列表。

    This time difference will not affect the performance of your program very much but it's nice to know which one is more efficient and how they work behind the scenes.

    这个时间差不会对程序的性能产生很大的影响,但是很高兴知道哪个效率更高以及它们如何在后台工作。

    Summary总结 (🔹 In Summary)

    You can create an empty list using an empty pair of square brackets [] or the type constructor list(), a built-in function that creates an empty list when no arguments are passed.

    您可以使用一对空的方括号[]或类型构造函数list()来创建一个空列表,该内置函数可以在不传递任何参数时创建一个空列表。

    Square brackets [] are commonly used in Python to create empty lists because it is faster and more concise.

    方括号[]在Python中通常用于创建空列表,因为它更快,更简洁。

    I really hope that you liked my article and found it helpful. Now you can create empty lists in your Python projects. Check out my online courses. Follow me on Twitter. 👍

    我真的希望您喜欢我的文章并发现它对您有所帮助。 现在,您可以在Python项目中创建空列表。 查看我的在线课程 。 在Twitter上关注我。 👍

    If you want to dive deeper into lists, you may like to read:

    如果您想更深入地研究清单,可以阅读以下内容:

    翻译自: https://www.freecodecamp.org/news/python-empty-list-tutorial-how-to-create-an-empty-list-in-python/

    python中创建空列表

    展开全文
  • python3 判断空列表 @(python3) 有判断列表是否为空的需求,试了好多方式,比如: a = [] if a is not None: COMMAND a = [] if a[0] is None: ...各种乱七八糟的逻辑,...以上这篇python3 判断列表是一个空列表
  • python如何创建空列表

    万次阅读 2020-01-09 07:32:12
    Python中创建新的空列表的方法有两种,如下: 或 list()比[]慢,因为: 1、有符号查找; 2、有函数调用;...

    v2-85a2dee5a6585da56e9227976ea7d5ac_b.jpg


    在Python中创建新的空列表的方法有两种,如下:

    v2-8ee5823b8fbdbfb3b0f4dcebb4c446dd_b.png

    v2-5d4c24714298f0338a2eda70d865cf70_b.png

    list()比[]慢,因为:

    1、有符号查找;

    2、有函数调用;

    3、然后,它必须检查是否传递了可迭代参数。

    但在大多数情况下,速度差异不会产生任何实际影响。

    下面是测试哪段代码更快:

    v2-9ae8014b6ffe57d880c0f0503918d794_b.png

    我更喜欢[],因为可读性是非常主观的。


    以上就是python如何创建空列表的详细内容

    如果大家如果在学习中遇到困难,想找一个Python学习交流环境,可以加入我们的Python学习圈,点击我加入吧,会节约很多时间,减少很多遇到的难题。

    展开全文
  • Python 创建多维空列表

    千次阅读 2020-07-23 01:04:45
    # 以三维空列表为例 3d_list = [ [ [] for j in range(9) ] for i in range(9) ] 列表推导式的生成值可以是空列表 [],因此只要利用列表推导式的复合循环即可轻松达到目的
    # 以三维空列表为例
    3d_list = [ [ [] for j in range(9) ] for i in range(9) ]

    列表推导式的生成值可以是空列表 [],因此只要利用列表推导式的复合循环即可轻松达到目的

    展开全文
  • I want a line of code which will create an empty list whose name is determined by an incrementing variable.Everywhere I"ve looked thus far has been unhelpful. They suggest instead something which...

    I want a line of code which will create an empty list whose name is determined by an incrementing variable.

    Everywhere I"ve looked thus far has been unhelpful. They suggest instead something which makes a list of empty lists or using a dictionary. This is not what I want, I want a line (or several) of code which just creates an empty list (which is not part of a dictionary or a list of lists, a stand alone entity). I want these lists to be distinct, distinguished by a variable which increments by 1 every time a new empty list is created.

    These empty lists can"t be made in one batch at the very beginning as I intend to make and delete these lists throughout a recursive function. I need to make multiple lists as my intention is for this function to descend to a new level of recursion but return later to the previous list. These are acting as temporary working lists which calculate a value for each item of an original list and then copy the result into a final list once it is found.

    str("list_" + i) = []

    If i = 1, then I would like this line of code to create an empty list with the name "list_1" which I can proceed to interact with throughout my script.

    Instead I"m met with "SyntaxError: can"t assign to function call"

    By all means let me know if I"m not making any sense at all and I will do my best to convey my request.

    解决方案

    Highly advise against this but this achieves what you want depending on your use case:

    globals()["list_" + str(i)] = []

    for i in range(5):

    globals()["list_" + str(i)] = []

    list_1

    []

    list_2

    []

    etc...

    Depending on your use case switch globals for locals and vice-versa.

    A better idea would be defaultdict

    from collections import defaultdict

    my_lists = defaultdict(list)

    Now you don"t have to initialize any list until you use it and every key comes with it"s value being a list already. For example:

    for i in range(5):

    my_lists["list_" + str(i)].append("foo")

    my_lists

    defaultdict(list,

    {"list_0": ["foo"],

    "list_1": ["foo"],

    "list_2": ["foo"],

    "list_3": ["foo"],

    "list_4": ["foo"]})

    展开全文
  • Python 判断一列表是否为空列表

    万次阅读 2019-07-31 14:36:02
    方法1(推荐):在Python中,False,0,’’,[],{}...方法3:让解释器再生成一个空列表,并将这个空列表与list_temp进行比较。此方法效率最低。 list_temp = [] print('方法1(推荐):在Python中,False,0,'',[],{},...
  • python3 判断列表是一个空列表

    万次阅读 2017-11-24 09:46:44
    python3 判断空列表@(python3)有判断列表是否为空的需求,试了好多方式,比如:a = [] if a is not None: COMMANDa = [] if a[0] is None: COMMAND各种乱七八糟的逻辑,老是无法满足。其实很简单。a = [] if a: ...
  • python创建空列表

    万次阅读 2017-11-12 23:45:30
    第一次写博客,请多多指教呀~写一函数创建一个空列表,参数为列表的大小,返回列表。def new(size): newlist = [] for i in range(0, size): newlist.append([]) return newlist 在命令行中执行
  • Python3 空列表添加数据

    千次阅读 2020-03-11 18:29:31
    Python3 空列表添加数据 Python3中空列表是不能直接调用append函数的,返回值会是None。 empty_list = [] print(empty_list.append(0)) 运行结果如下: 要向空列表中添加数据,“+”来组合列表: empty_list = [] ...
  • # 空列表创建方式、 lst1 = [] lst12 =list() #空字典创建方式 dicr1 = {} dictr = dict() # 空元祖创建方式 t9 = () t91 = tuple()
  • 主要介绍了Python创建空列表的字典2种方法详解,需要的朋友可以参考下
  • python:关于空列表的用法错误

    千次阅读 2019-12-19 21:42:54
    list =[] #定义一个空列表 #想把新建的列表创建为8元素且每元素为0的列表 for i in range(8): list[i] = 0 结果输出报错: Traceback (most recent call last): File "<stdin>", line 2, in <module...
  • 我们有时会需要一个空列表,用来在指定索引处赋值,比如我有一个空列表 L ,现在我需要直接在第7位置赋值(L[7]=666),而不是常规的顺序赋值(用append追加元素),这时要怎么生成这个空列表呢?方法很简单,代码...
  • Python中,一个空列表,空元组,空字符串,空字典的布尔值为False,但是不是None,具体如下所示: 如上所示,Python中判断一列表是否为空,切不可用是否None来判断,而应该直接判断,如if a,如果a为空列表,...
  • Python学习之空列表[]与None

    千次阅读 2018-11-07 14:48:49
    空列表也是列表,None类型只有None一值 >>> L1, L2 = None, [] >>> L1, L2 (None, []) >>> L1 == None True >>> L1 is None True >>> L2 == None False >>> L2 is None False >>> L2 == [] True
  • 这里
  • 定义 元组(tuple):  不可变序列,一旦建立不能修改元组中的元素。 列表[list]:  可变序列,可以添加和删除其中的元素。...空元组、空列表、空字典、空集合 >>> a=() >>> b=[] &
  • python 变量初始化空列表

    千次阅读 2018-11-21 17:33:27
    python 不能写new_loss=old_loss=[] 这样 两变量实际上是同一list 要分开写new_loss=[] Old_loss=[] 以下列数据文件为例: def analyze_mmr(fn): #初始化方法一 new_loss = [] old_loss = [] #初始化...
  • a,b,c,d,e,f,g 变量都赋值为空列表 传统: a=[] b=[] c=[] d=[] e=[] f=[] g=[] for循环: a,b,c,d,e,f,g=([] for i in range(7))
  • Python 将一个列表置为

    千次阅读 2019-07-31 13:41:23
    方法一:调用clear方法(推荐),在原有的列表中进行改动,开销较小。 方法二:引用赋值一个空列表,将原有的列表丢垃圾回收器,并创建一新列表,开销较大。
  • 1.list的创建: l = list() 或者: l = [] 2.list中元素的创建和表达 fruits = ['apple', 'banana', 'pear', 'grapes', 'pineapple', 'watermelon'] fruits[2] #从0开始数起,第三元素 pear 3....
  • Python 创建空列表的字典

    千次阅读 2015-09-08 10:35:21
    如果要创建一这样的字典,该怎么做?{1:[], 2:[], 3:[], 4:[]}下面对比两种方法的异同

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 207,599
精华内容 83,039
关键字:

python给个空列表

python 订阅