天天看點

python中字典清單元組_Python中的清單和元組

python中字典清單元組

Lists and tuples are arguably Python’s most versatile, useful data types. You will find them in virtually every nontrivial Python program.

清單和元組可以說是Python最通用,最有用的資料類型。 您幾乎可以在每個平凡的Python程式中找到它們。

Here’s what you’ll learn in this tutorial: You’ll cover the important characteristics of lists and tuples. You’ll learn how to define them and how to manipulate them. When you’re finished, you should have a good feel for when and how to use these object types in a Python program.

這是在本教程中将學到的内容:您将介紹清單和元組的重要特征。 您将學習如何定義它們以及如何操作它們。 完成後,您應該對何時以及如何在Python程式中使用這些對象類型有很好的了解。

Python清單 (Python Lists)

In short, a list is a collection of arbitrary objects, somewhat akin to an array in many other programming languages but more flexible. Lists are defined in Python by enclosing a comma-separated sequence of objects in square brackets (

[]

), as shown below:

簡而言之,清單是任意對象的集合,類似于許多其他程式設計語言中的數組,但更為靈活。 清單是在Python中定義的,方法是将用逗号分隔的對象序列括在方括号(

[]

)中,如下所示:

>> a = ['foo', 'bar', 'baz', 'qux']

>> a = ['foo', 'bar', 'baz', 'qux']

>>> >>>  printprint (( aa )
)
['foo', 'bar', 'baz', 'qux']
['foo', 'bar', 'baz', 'qux']
>>> >>>  a
a
['foo', 'bar', 'baz', 'qux']
['foo', 'bar', 'baz', 'qux']
           

The important characteristics of Python lists are as follows:

Python清單的重要特征如下:

  • Lists are ordered.
  • Lists can contain any arbitrary objects.
  • List elements can be accessed by index.
  • Lists can be nested to arbitrary depth.
  • Lists are mutable.
  • Lists are dynamic.
  • 清單是有序的。
  • 清單可以包含任何任意對象。
  • 清單元素可以通過索引通路。
  • 清單可以嵌套到任意深度。
  • 清單是可變的。
  • 清單是動态的。

Each of these features is examined in more detail below.

這些功能中的每一個都将在下面更詳細地研究。

清單已排序 (Lists Are Ordered)

A list is not merely a collection of objects. It is an ordered collection of objects. The order in which you specify the elements when you define a list is an innate characteristic of that list and is maintained for that list’s lifetime. (You will see a Python data type that is not ordered in the next tutorial on dictionaries.)

清單不僅是對象的集合。 它是對象的有序集合。 定義清單時指定元素的順序是該清單的固有特性,并在該清單的生命周期内保持不變。 (您将看到在下一本關于字典的教程中未排序的Python資料類型。)

Lists that have the same elements in a different order are not the same:

具有相同元素但順序不同的清單是不同的:

清單可以包含任意對象 (Lists Can Contain Arbitrary Objects)

A list can contain any assortment of objects. The elements of a list can all be the same type:

清單可以包含任何種類的對象。 清單的元素都可以是同一類型:

>>> >>>  a a = = [[ 22 , , 44 , , 66 , , 88 ]
]
>>> >>>  a
a
[2, 4, 6, 8]
[2, 4, 6, 8]
           

Or the elements can be of varying types:

或者元素可以是不同的類型:

Lists can even contain complex objects, like functions, classes, and modules, which you will learn about in upcoming tutorials:

清單甚至可以包含複雜的對象,例如函數,類和子產品,您将在接下來的教程中了解這些對象:

>>> >>>  int
int
<class 'int'>
<class 'int'>
>>> >>>  len
len
<built-in function len>
<built-in function len>
>>> >>>  def def foofoo ():
():
...     ...     pass
pass
...
...
>>> >>>  foo
foo
<function foo at 0x035B9030>
<function foo at 0x035B9030>
>>> >>>  import import math
math
>>> >>>  math
math
<module 'math' (built-in)>

<module 'math' (built-in)>

>>> >>>  a a = = [[ intint , , lenlen , , foofoo , , mathmath ]
]
>>> >>>  a
a
[<class 'int'>, <built-in function len>, <function foo at 0x02CA2618>,
[<class 'int'>, <built-in function len>, <function foo at 0x02CA2618>,
<module 'math' (built-in)>]
<module 'math' (built-in)>]
           

A list can contain any number of objects, from zero to as many as your computer’s memory will allow:

清單可以包含任意數量的對象,從零到您的計算機記憶體允許的數量:

(A list with a single object is sometimes referred to as a singleton list.)

(具有單個對象的清單有時稱為單例清單。)

List objects needn’t be unique. A given object can appear in a list multiple times:

清單對象不必唯一。 給定的對象可以多次出現在清單中:

>>> >>>  a a = = [[ 'bark''bark' , , 'meow''meow' , , 'woof''woof' , , 'bark''bark' , , 'cheep''cheep' , , 'bark''bark' ]
]
>>> >>>  a
a
['bark', 'meow', 'woof', 'bark', 'cheep', 'bark']
['bark', 'meow', 'woof', 'bark', 'cheep', 'bark']
           

清單元素可以通過索引通路 (List Elements Can Be Accessed by Index)

Individual elements in a list can be accessed using an index in square brackets. This is exactly analogous to accessing individual characters in a string. List indexing is zero-based as it is with strings.

清單中的各個元素可以使用方括号中的索引進行通路。 這完全類似于通路字元串中的單個字元。 清單索引與字元串一樣,都是從零開始的。

Consider the following list:

考慮以下清單:

The indices for the elements in

a

are shown below:

a

中元素的索引如下所示:

python中字典清單元組_Python中的清單和元組

List Indices 清單索引

Here is Python code to access some elements of

a

:

下面是Python代碼通路的一些元素

a

>>> >>>  aa [[ 00 ]
]
'foo'
'foo'
>>> >>>  aa [[ 22 ]
]
'baz'
'baz'
>>> >>>  aa [[ 55 ]
]
'corge'
'corge'
           

Virtually everything about string indexing works similarly for lists. For example, a negative list index counts from the end of the list:

實際上,有關字元串索引的所有内容對于清單而言都類似。 例如,負清單索引從清單的末尾開始計數:

python中字典清單元組_Python中的清單和元組

Negative List Indexing 負面清單索引

Slicing also works. If

a

is a list, the expression

a[m:n]

returns the portion of

a

from index

m

to, but not including, index

n

:

切片也可以。 如果

a

是一個清單,則表達式

a[m:n]

傳回

a

從索引

m

到但不包括索引

n

>>> >>>  a a = = [[ 'foo''foo' , , 'bar''bar' , , 'baz''baz' , , 'qux''qux' , , 'quux''quux' , , 'corge''corge' ]

]

>>> >>>  aa [[ 22 :: 55 ]
]
['baz', 'qux', 'quux']
['baz', 'qux', 'quux']
           

Other features of string slicing work analogously for list slicing as well:

字元串切片的其他功能也類似地用于清單切片:

  • Both positive and negative indices can be specified:
  • Omitting the first index starts the slice at the beginning of the list, and omitting the second index extends the slice to the end of the list:
    >>> print(a[:4], a[0:4])
    ['foo', 'bar', 'baz', 'qux'] ['foo', 'bar', 'baz', 'qux']
    >>> print(a[2:], a[2:len(a)])
    ['baz', 'qux', 'quux', 'corge'] ['baz', 'qux', 'quux', 'corge']
    
    >>> a[:4] + a[4:]
    ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
    >>> a[:4] + a[4:] == a
    True
               
  • You can specify a stride—either positive or negative:
  • The syntax for reversing a list works the same way it does for strings:
    >>> a[::-1]
    ['corge', 'quux', 'qux', 'baz', 'bar', 'foo']
               
  • The

    [:]

    syntax works for lists. However, there is an important difference between how this operation works with a list and how it works with a string.

    If

    s

    is a string,

    s[:]

    returns a reference to the same object:

    Conversely, if

    a

    is a list,

    a[:]

    returns a new object that is a copy of

    a

    :
    >>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
    >>> a[:]
    ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
    >>> a[:] is a
    False
               
  • 正負索引均可指定:
  • 省略第一個索引會在清單的開頭開始切片,而省略第二個索引會将切片擴充到清單的末尾:
    >>>  print ( a [: 4 ], a [ 0 : 4 ])
    ['foo', 'bar', 'baz', 'qux'] ['foo', 'bar', 'baz', 'qux']
    >>>  print ( a [ 2 :], a [ 2 : len ( a )])
    ['baz', 'qux', 'quux', 'corge'] ['baz', 'qux', 'quux', 'corge']
    
    >>>  a [: 4 ] + a [ 4 :]
    ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
    >>>  a [: 4 ] + a [ 4 :] == a
    True
               
  • 您可以指定一個步幅(正數或負數):
  • 反轉清單的文法與處理字元串的方法相同:
    >>>  a [:: - 1 ]
    ['corge', 'quux', 'qux', 'baz', 'bar', 'foo']
               
  • [:]

    文法适用于清單。 但是,此操作如何與清單一起使用以及如何與字元串一起使用之間存在重要差別。

    如果

    s

    是字元串,則

    s[:]

    傳回對同一對象的引用:

    相反,如果

    a

    是一個清單,

    a[:]

    傳回一個新對象的副本

    a

    >>>  a = [ 'foo' , 'bar' , 'baz' , 'qux' , 'quux' , 'corge' ]
    >>>  a [:]
    ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
    >>>  a [:] is a
    False
               

Several Python operators and built-in functions can also be used with lists in ways that are analogous to strings:

幾個Python運算符和内置函數也可以類似于字元串的方式與清單一起使用:

  • The

    in

    and

    not in

    operators:
  • The concatenation (

    +

    ) and replication (

    *

    ) operators:
    >>> a
    ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
    
    >>> a + ['grault', 'garply']
    ['foo', 'bar', 'baz', 'qux', 'quux', 'corge', 'grault', 'garply']
    >>> a * 2
    ['foo', 'bar', 'baz', 'qux', 'quux', 'corge', 'foo', 'bar', 'baz',
    'qux', 'quux', 'corge']
               
  • The

    len()

    ,

    min()

    , and

    max()

    functions:
  • in

    not in

    運算符:
    >>>  a
    ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
    
    >>>  'qux' in a
    True
    >>>  'thud' not in a
    True
               
  • 串聯(

    +

    )和複制(

    *

    )運算符:
  • len()

    min()

    max()

    函數:
    >>>  a
    ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
    
    >>>  len ( a )
    6
    >>>  min ( a )
    'bar'
    >>>  max ( a )
    'qux'
               

It’s not an accident that strings and lists behave so similarly. They are both special cases of a more general object type called an iterable, which you will encounter in more detail in the upcoming tutorial on definite iteration.

字元串和清單的行為如此相似并非偶然。 它們都是更常見的對象類型(稱為Iterable)的特例,您将在即将到來的有關确定疊代的教程中更詳細地介紹這些對象。

By the way, in each example above, the list is always assigned to a variable before an operation is performed on it. But you can operate on a list literal as well:

順便說一下,在上面的每個示例中,始終在對變量執行操作之前将清單配置設定給變量。 但是您也可以對清單文字進行操作:

For that matter, you can do likewise with a string literal:

為此,您也可以對字元串文字進行處理:

>>> >>>  'If Comrade Napoleon says it, it must be right.''If Comrade Napoleon says it, it must be right.' [::[:: -- 11 ]
]
'.thgir eb tsum ti ,ti syas noelopaN edarmoC fI'
'.thgir eb tsum ti ,ti syas noelopaN edarmoC fI'
           

清單可以嵌套 (Lists Can Be Nested)

You have seen that an element in a list can be any sort of object. That includes another list. A list can contain sublists, which in turn can contain sublists themselves, and so on to arbitrary depth.

您已經看到清單中的元素可以是任何種類的對象。 其中包括另一個清單。 清單可以包含子清單,而子清單又可以包含子清單本身,依此類推可以任意深度。

Consider this (admittedly contrived) example:

考慮以下(公認的)示例:

The object structure that

x

references is diagrammed below:

x

引用的對象結構如下圖所示:

python中字典清單元組_Python中的清單和元組

A Nested List 嵌套清單

x[0]

,

x[2]

, and

x[4]

are strings, each one character long:

x[0]

x[2]

x[4]

是字元串,每個字元長:

>>> >>>  printprint (( xx [[ 00 ], ], xx [[ 22 ], ], xx [[ 44 ])
])
a g j
a g j
           

But

x[1]

and

x[3]

are sublists:

但是

x[1]

x[3]

是子清單:

To access the items in a sublist, simply append an additional index:

要通路子清單中的項目,隻需附加一個附加索引:

>>> >>>  xx [[ 11 ]
]
['bb', ['ccc', 'ddd'], 'ee', 'ff']

['bb', ['ccc', 'ddd'], 'ee', 'ff']

>>> >>>  xx [[ 11 ][][ 00 ]
]
'bb'
'bb'
>>> >>>  xx [[ 11 ][][ 11 ]
]
['ccc', 'ddd']
['ccc', 'ddd']
>>> >>>  xx [[ 11 ][][ 22 ]
]
'ee'
'ee'
>>> >>>  xx [[ 11 ][][ 33 ]
]
'ff'

'ff'

>>> >>>  xx [[ 33 ]
]
['hh', 'ii']
['hh', 'ii']
>>> >>>  printprint (( xx [[ 33 ][][ 00 ], ], xx [[ 33 ][][ 11 ])
])
hh ii
hh ii
           

x[1][1]

is yet another sublist, so adding one more index accesses its elements:

x[1][1]

是另一個子清單,是以再添加一個索引即可通路其元素:

There is no limit, short of the extent of your computer’s memory, to the depth or complexity with which lists can be nested in this way.

除了計算機記憶體的大小外,清單可以以這種方式嵌套的深度或複雜性沒有限制。

All the usual syntax regarding indices and slicing applies to sublists as well:

關于索引和切片的所有正常文法也适用于子清單:

>>> >>>  xx [[ 11 ][][ 11 ][][ -- 11 ]
]
'ddd'
'ddd'
>>> >>>  xx [[ 11 ][][ 11 :: 33 ]
]
[['ccc', 'ddd'], 'ee']
[['ccc', 'ddd'], 'ee']
>>> >>>  xx [[ 33 ][::][:: -- 11 ]
]
['ii', 'hh']
['ii', 'hh']
           

However, be aware that operators and functions apply to only the list at the level you specify and are not recursive. Consider what happens when you query the length of

x

using

len()

:

但是,請注意,運算符和函數僅适用于您指定級别的清單,并且不是遞歸的。 考慮當您使用

len()

查詢

x

的長度時會發生什麼:

x

has only five elements—three strings and two sublists. The individual elements in the sublists don’t count toward

x

’s length.

x

隻有五個元素-三個字元串和兩個子清單。 子清單中的各個元素不計入

x

的長度。

You’d encounter a similar situation when using the

in

operator:

使用

in

運算符時,您會遇到類似的情況:

>>> >>>  'ddd' 'ddd' in in x
x
False
False
>>> >>>  'ddd' 'ddd' in in xx [[ 11 ]
]
False
False
>>> >>>  'ddd' 'ddd' in in xx [[ 11 ][][ 11 ]
]
True
True
           

'ddd'

is not one of the elements in

x

or

x[1]

. It is only directly an element in the sublist

x[1][1]

. An individual element in a sublist does not count as an element of the parent list(s).

'ddd'

不是

x

x[1]

中的元素之一。 它僅是子清單

x[1][1]

中的一個直接元素。 子清單中的單個元素不算作父清單的元素。

清單是可變的 (Lists Are Mutable)

Most of the data types you have encountered so far have been atomic types. Integer or float objects, for example, are primitive units that can’t be further broken down. These types are immutable, meaning that they can’t be changed once they have been assigned. It doesn’t make much sense to think of changing the value of an integer. If you want a different integer, you just assign a different one.

到目前為止,您遇到的大多數資料類型都是原子類型。 例如,整數或浮點對象是無法進一步細分的基本單元。 這些類型是不可變的,這意味着一旦配置設定它們就無法更改。 考慮更改整數的值沒有多大意義。 如果要使用其他整數,隻需配置設定其他整數即可。

By contrast, the string type is a composite type. Strings are reducible to smaller parts—the component characters. It might make sense to think of changing the characters in a string. But you can’t. In Python, strings are also immutable.

相反,字元串類型是複合類型。 字元串可簡化為較小的部分-組成字元。 考慮更改字元串中的字元可能很有意義。 但是你不能。 在Python中,字元串也是不可變的。

The list is the first mutable data type you have encountered. Once a list has been created, elements can be added, deleted, shifted, and moved around at will. Python provides a wide range of ways to modify lists.

該清單是您遇到的第一個可變資料類型。 建立清單後,可以随意添加,删除,移動和移動元素。 Python提供了多種修改清單的方法。

修改單個清單值 (Modifying a Single List Value)

A single value in a list can be replaced by indexing and simple assignment:

清單中的單個值可以用索引和簡單指派代替:

You may recall from the tutorial Strings and Character Data in Python that you can’t do this with a string:

您可能會從Python的字元串和字元資料教程中回想起您無法使用字元串進行此操作:

>>> >>>  s s = = 'foobarbaz'
'foobarbaz'
>>> >>>  ss [[ 22 ] ] = = 'x'
'x'
Traceback (most recent call last):
  File Traceback (most recent call last):
  File "<stdin>", line "<stdin>" , line 1, in 1 , in <module>
<module>
TypeError: TypeError : 'str' object does not support item assignment
'str' object does not support item assignment
           

A list item can be deleted with the

del

command:

可以使用

del

指令删除清單項:

修改多個清單值 (Modifying Multiple List Values)

What if you want to change several contiguous elements in a list at one time? Python allows this with slice assignment, which has the following syntax:

如果要一次更改清單中的幾個連續元素怎麼辦? Python允許通過切片配置設定來實作這一點,它具有以下文法:

aa [[ mm :: nn ] ] = = << iterableiterable >
>
           

Again, for the moment, think of an iterable as a list. This assignment replaces the specified slice of

a

with

<iterable>

:

再次,暫時将可疊代項視為清單。 這種配置設定替換的指定切片

a

<iterable>

The number of elements inserted need not be equal to the number replaced. Python just grows or shrinks the list as needed.

插入的元素數量不必等于替換的數量。 Python隻是根據需要增加或縮小清單。

You can insert multiple elements in place of a single element—just use a slice that denotes only one element:

您可以插入多個元素來代替單個元素-隻需使用僅表示一個元素的切片即可:

>>> >>>  a a = = [[ 11 , , 22 , , 33 ]
]
>>> >>>  aa [[ 11 :: 22 ] ] = = [[ 2.12.1 , , 2.22.2 , , 2.32.3 ]
]
>>> >>>  a
a
[1, 2.1, 2.2, 2.3, 3]
[1, 2.1, 2.2, 2.3, 3]
           

Note that this is not the same as replacing the single element with a list:

請注意,這與用清單替換單個元素不同:

You can also insert elements into a list without removing anything. Simply specify a slice of the form

[n:n]

(a zero-length slice) at the desired index:

您也可以在不删除任何内容的情況下将元素插入清單。 隻需在所需的索引處指定

[n:n]

形式的切片(零長度切片)即可:

>>> >>>  a a = = [[ 11 , , 22 , , 77 , , 88 ]
]
>>> >>>  aa [[ 22 :: 22 ] ] = = [[ 33 , , 44 , , 55 , , 66 ]
]
>>> >>>  a
a
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
           

You can delete multiple elements out of the middle of a list by assigning the appropriate slice to an empty list. You can also use the

del

statement with the same slice:

您可以通過将适當的切片配置設定給空清單來删除清單中間的多個元素。 您還可以将

del

語句用于同一切片:

在清單之前或之後添加項目 (Prepending or Appending Items to a List)

Additional items can be added to the start or end of a list using the

+

concatenation operator or the

+=

augmented assignment operator:

可以使用

+

串聯運算符或

+=

擴充指派運算符将其他項添加到清單的開頭或結尾:

>>> >>>  a a = = [[ 'foo''foo' , , 'bar''bar' , , 'baz''baz' , , 'qux''qux' , , 'quux''quux' , , 'corge''corge' ]

]

>>> >>>  a a += += [[ 'grault''grault' , , 'garply''garply' ]
]
>>> >>>  a
a
['foo', 'bar', 'baz', 'qux', 'quux', 'corge', 'grault', 'garply']

['foo', 'bar', 'baz', 'qux', 'quux', 'corge', 'grault', 'garply']

>>> >>>  a a = = [[ 'foo''foo' , , 'bar''bar' , , 'baz''baz' , , 'qux''qux' , , 'quux''quux' , , 'corge''corge' ]

]

>>> >>>  a a = = [[ 1010 , , 2020 ] ] + + a
a
>>> >>>  a
a
[10, 20, 'foo', 'bar', 'baz', 'qux', 'quux', 'corge']
[10, 20, 'foo', 'bar', 'baz', 'qux', 'quux', 'corge']
           

Note that a list must be concatenated with another list, so if you want to add only one element, you need to specify it as a singleton list:

請注意,一個清單必須與另一個清單串聯,是以,如果您隻想添加一個元素,則需要将其指定為單例清單:

Note: Technically, it isn’t quite correct to say a list must be concatenated with another list. More precisely, a list must be concatenated with an object that is iterable. Of course, lists are iterable, so it works to concatenate a list with another list.

注意:從技術上講,說一個清單必須與另一個清單串聯是不太正确的。 更準确地說,清單必須與可疊代的對象連接配接在一起。 當然,清單是可疊代的,是以它可以将一個清單與另一個清單連接配接在一起。

Strings are iterable also. But watch what happens when you concatenate a string onto a list:

字元串也是可疊代的。 但是請注意将字元串連接配接到清單時會發生什麼:

>>> >>>  a a = = [[ 'foo''foo' , , 'bar''bar' , , 'baz''baz' , , 'qux''qux' , , 'quux''quux' ]
]
>>> >>>  a a += += 'corge'
'corge'
>>> >>>  a
a
['foo', 'bar', 'baz', 'qux', 'quux', 'c', 'o', 'r', 'g', 'e']
['foo', 'bar', 'baz', 'qux', 'quux', 'c', 'o', 'r', 'g', 'e']
           

This result is perhaps not quite what you expected. When a string is iterated through, the result is a list of its component characters. In the above example, what gets concatenated onto list

a

is a list of the characters in the string

'corge'

.

此結果可能與您預期的不太一樣。 周遊字元串時,結果是其組成字元的清單。 在上面的示例中,連接配接到清單

a

是字元串

'corge'

中的字元清單。

If you really want to add just the single string

'corge'

to the end of the list, you need to specify it as a singleton list:

如果您确實隻想将單個字元串

'corge'

到清單的末尾,則需要将其指定為單例清單:

If this seems mysterious, don’t fret too much. You’ll learn about the ins and outs of iterables in the tutorial on definite iteration.

如果這看起來很神秘,請不要擔心太多。 您将在有關确定疊代的教程中了解可疊代的内容。

修改清單的方法 (Methods That Modify a List)

Finally, Python supplies several built-in methods that can be used to modify lists. Information on these methods is detailed below.

最後,Python提供了幾種可用于修改清單的内置方法。 這些方法的詳細資訊如下。

Note: The string methods you saw in the previous tutorial did not modify the target string directly. That is because strings are immutable. Instead, string methods return a new string object that is modified as directed by the method. They leave the original target string unchanged:

注意:在上一教程中看到的字元串方法沒有直接修改目标字元串。 那是因為字元串是不可變的。 而是,字元串方法傳回一個新的字元串對象,該對象按照方法的訓示進行了修改。 它們使原始目标字元串保持不變:

>>> >>>  s s = = 'foobar'
'foobar'
>>> >>>  t t = = ss .. upperupper ()
()
>>> >>>  printprint (( ss , , tt )
)
foobar FOOBAR
foobar FOOBAR
           

List methods are different. Because lists are mutable, the list methods shown here modify the target list in place.

清單方法不同。 由于清單是可變的,是以此處顯示的清單方法會修改目标清單。

a.append(<obj>)

a.append(<obj>)

Appends an object to a list.

将對象追加到清單。

a.append(<obj>)

appends object

<obj>

to the end of list

a

:

a.append(<obj>)

将對象

<obj>

追加到清單

a

的末尾:

Remember, list methods modify the target list in place. They do not return a new list:

請記住,清單方法會适當地修改目标清單。 他們不傳回新清單:

>>> >>>  a a = = [[ 'a''a' , , 'b''b' ]
]
>>> >>>  x x = = aa .. appendappend (( 123123 )
)
>>> >>>  printprint (( xx )
)
None
None
>>> >>>  a
a
['a', 'b', 123]
['a', 'b', 123]
           

Remember that when the

+

operator is used to concatenate to a list, if the target operand is an iterable, then its elements are broken out and appended to the list individually:

請記住,當使用

+

運算符連接配接到清單時,如果目标操作數是可疊代的,則分解其元素并将其分别附加到清單中:

The

.append()

method does not work that way! If an iterable is appended to a list with

.append()

, it is added as a single object:

.append()

方法無法正常工作! 如果使用

.append()

将iterable追加到清單中,則會将其作為單個對象添加:

>>> >>>  a a = = [[ 'a''a' , , 'b''b' ]
]
>>> >>>  aa .. appendappend ([([ 11 , , 22 , , 33 ])
])
>>> >>>  a
a
['a', 'b', [1, 2, 3]]
['a', 'b', [1, 2, 3]]
           

Thus, with

.append()

, you can append a string as a single entity:

是以,使用

.append()

,您可以将字元串附加為單個實體:

a.extend(<iterable>)

a.extend(<iterable>)

Extends a list with the objects from an iterable.

用可疊代對象擴充清單。

Yes, this is probably what you think it is.

.extend()

also adds to the end of a list, but the argument is expected to be an iterable. The items in

<iterable>

are added individually:

是的,這可能就是您的想法。

.extend()

也會添加到清單的末尾,但是該參數應該是可疊代的。

<iterable>

中的項目是分别添加的:

>>> >>>  a a = = [[ 'a''a' , , 'b''b' ]
]
>>> >>>  aa .. extendextend ([([ 11 , , 22 , , 33 ])
])
>>> >>>  a
a
['a', 'b', 1, 2, 3]
['a', 'b', 1, 2, 3]
           

In other words,

.extend()

behaves like the

+

operator. More precisely, since it modifies the list in place, it behaves like the

+=

operator:

換句話說,

.extend()

行為類似于

+

運算符。 更準确地說,由于它修改了清單,是以其行為類似于

+=

運算符:

a.insert(<index>, <obj>)

a.insert(<index>, <obj>)

Inserts an object into a list.

将對象插入清單。

a.insert(<index>, <obj>)

inserts object

<obj>

into list

a

at the specified

<index>

. Following the method call,

a[<index>]

is

<obj>

, and the remaining list elements are pushed to the right:

a.insert(<index>, <obj>)

将對象

<obj>

插入到指定

<index>

處的清單

a

中。 在方法調用之後,

a[<index>]

<obj>

,其餘清單元素被推到右邊:

>>> >>>  a a = = [[ 'foo''foo' , , 'bar''bar' , , 'baz''baz' , , 'qux''qux' , , 'quux''quux' , , 'corge''corge' ]
]
>>> >>>  aa .. insertinsert (( 33 , , 3.141593.14159 )
)
>>> >>>  aa [[ 33 ]
]
3.14159
3.14159
>>> >>>  a
a
['foo', 'bar', 'baz', 3.14159, 'qux', 'quux', 'corge']
['foo', 'bar', 'baz', 3.14159, 'qux', 'quux', 'corge']
           

a.remove(<obj>)

a.remove(<obj>)

Removes an object from a list.

從清單中删除對象。

a.remove(<obj>)

removes object

<obj>

from list

a

. If

<obj>

isn’t in

a

, an exception is raised:

a.remove(<obj>)

從清單

a

删除對象

<obj>

。 如果

<obj>

不在

a

,将引發一個例外:

a.pop(index=-1)

a.pop(index=-1)

Removes an element from a list.

從清單中删除一個元素。

This method differs from

.remove()

in two ways:

此方法與

.remove()

有兩點不同:

  1. You specify the index of the item to remove, rather than the object itself.
  2. The method returns a value: the item that was removed.
  1. 您指定要删除的項目的索引,而不是對象本身。
  2. 該方法傳回一個值:被删除的項目。

a.pop()

simply removes the last item in the list:

a.pop()

隻是删除清單中的最後一項:

>>> >>>  a a = = [[ 'foo''foo' , , 'bar''bar' , , 'baz''baz' , , 'qux''qux' , , 'quux''quux' , , 'corge''corge' ]

]

>>> >>>  aa .. poppop ()
()
'corge'
'corge'
>>> >>>  a
a
['foo', 'bar', 'baz', 'qux', 'quux']

['foo', 'bar', 'baz', 'qux', 'quux']

>>> >>>  aa .. poppop ()
()
'quux'
'quux'
>>> >>>  a
a
['foo', 'bar', 'baz', 'qux']
['foo', 'bar', 'baz', 'qux']
           

If the optional

<index>

parameter is specified, the item at that index is removed and returned.

<index>

may be negative, as with string and list indexing:

如果指定了可選的

<index>

參數,那麼将删除并傳回該索引處的項目。

<index>

可能為負,如字元串和清單索引:

<index>

defaults to

-1

, so

a.pop(-1)

is equivalent to

a.pop()

.

<index>

預設為

-1

,是以

a.pop(-1)

等同于

a.pop()

清單是動态的 (Lists Are Dynamic)

This tutorial began with a list of six defining characteristics of Python lists. The last one is that lists are dynamic. You have seen many examples of this in the sections above. When items are added to a list, it grows as needed:

本教程首先列出了Python清單的六個定義特征。 最後一個是清單是動态的。 在上面的部分中,您已經看到了許多示例。 将項目添加到清單後,它會根據需要增長:

>>> >>>  a a = = [[ 'foo''foo' , , 'bar''bar' , , 'baz''baz' , , 'qux''qux' , , 'quux''quux' , , 'corge''corge' ]

]

>>> >>>  aa [[ 22 :: 22 ] ] = = [[ 11 , , 22 , , 33 ]
]
>>> >>>  a a += += [[ 3.141593.14159 ]
]
>>> >>>  a
a
['foo', 'bar', 1, 2, 3, 'baz', 'qux', 'quux', 'corge', 3.14159]
['foo', 'bar', 1, 2, 3, 'baz', 'qux', 'quux', 'corge', 3.14159]
           

Similarly, a list shrinks to accommodate the removal of items:

同樣,清單會縮小以容納項目的删除:

Python元組 (Python Tuples)

Python provides another type that is an ordered collection of objects, called a tuple.

Python提供了另一種類型,即對象的有序集合,稱為元組。

Pronunciation varies depending on whom you ask. Some pronounce it as though it were spelled “too-ple” (rhyming with “Mott the Hoople”), and others as though it were spelled “tup-ple” (rhyming with “supple”). My inclination is the latter, since it presumably derives from the same origin as “quintuple,” “sextuple,” “octuple,” and so on, and everyone I know pronounces these latter as though they rhymed with “supple.”

發音取決于您問的人。 有些人說它好像被拼寫為“ to-ple”(用“ Mott the Hoople”押韻),而另一些人則說它被拼寫為“ tup-ple”(押韻為“ supple”)。 我的傾向是後者,因為它大概來自與“五重奏”,“八重奏”,“八重奏”等相同的起源,而且我認識的每個人都将後者稱為“柔順”。

定義和使用元組 (Defining and Using Tuples)

Tuples are identical to lists in all respects, except for the following properties:

元組在所有方面均與清單相同,但以下屬性除外:

  • Tuples are defined by enclosing the elements in parentheses (

    ()

    ) instead of square brackets (

    []

    ).
  • Tuples are immutable.
  • 通過将元素括在圓括号(

    ()

    )中而不是方括号(

    []

    )中來定義元組。
  • 元組是不可變的。

Here is a short example showing a tuple definition, indexing, and slicing:

這是一個簡短的示例,顯示元組定義,索引和切片:

>>> >>>  t t = = (( 'foo''foo' , , 'bar''bar' , , 'baz''baz' , , 'qux''qux' , , 'quux''quux' , , 'corge''corge' )
)
>>> >>>  t
t
('foo', 'bar', 'baz', 'qux', 'quux', 'corge')

('foo', 'bar', 'baz', 'qux', 'quux', 'corge')

>>> >>>  tt [[ 00 ]
]
'foo'
'foo'
>>> >>>  tt [[ -- 11 ]
]
'corge'
'corge'
>>> >>>  tt [[ 11 :::: 22 ]
]
('bar', 'qux', 'corge')
('bar', 'qux', 'corge')
           

Never fear! Our favorite string and list reversal mechanism works for tuples as well:

從不畏懼! 我們最喜歡的字元串和清單反轉機制也适用于元組:

Note: Even though tuples are defined using parentheses, you still index and slice tuples using square brackets, just as for strings and lists.

注意:即使元組是使用括号定義的,您仍然可以使用方括号對元組進行索引和切片,就像字元串和清單一樣。

Everything you’ve learned about lists—they are ordered, they can contain arbitrary objects, they can be indexed and sliced, they can be nested—is true of tuples as well. But they can’t be modified:

關于元組的所有知識(它們都是有序的,它們可以包含任意對象,可以對它們進行索引和切片,可以嵌套)也适用于元組。 但是它們不能被修改:

>>> >>>  t t = = (( 'foo''foo' , , 'bar''bar' , , 'baz''baz' , , 'qux''qux' , , 'quux''quux' , , 'corge''corge' )
)
>>> >>>  tt [[ 22 ] ] = = 'Bark!'
'Bark!'
Traceback (most recent call last):
  File Traceback (most recent call last):
  File "<pyshell#65>", line "<pyshell#65>" , line 1, in 1 , in <module>
    <module>
    tt [[ 22 ] ] = = 'Bark!'
'Bark!'
TypeError: TypeError : 'tuple' object does not support item assignment
'tuple' object does not support item assignment
           

Why use a tuple instead of a list?

為什麼使用元組而不是清單?

  • Program execution is faster when manipulating a tuple than it is for the equivalent list. (This is probably not going to be noticeable when the list or tuple is small.)
  • Sometimes you don’t want data to be modified. If the values in the collection are meant to remain constant for the life of the program, using a tuple instead of a list guards against accidental modification.
  • There is another Python data type that you will encounter shortly called a dictionary, which requires as one of its components a value that is of an immutable type. A tuple can be used for this purpose, whereas a list can’t be.
  • 處理元組時,程式執行的速度比等效清單更快。 (當清單或元組較小時,這可能不會引起注意。)
  • 有時您不希望修改資料。 如果集合中的值在程式生命期内保持恒定,則使用元組而不是清單可以防止意外修改。
  • 您将很快遇到另一種Python資料類型,稱為字典,它需要一個不可變類型的值作為其元件之一。 元組可以用于此目的,而清單則不能。

In a Python REPL session, you can display the values of several objects simultaneously by entering them directly at the

>>>

prompt, separated by commas:

在Python REPL會話中,可以通過在

>>>

提示符下直接輸入多個對象的值(以逗号分隔)來同時顯示多個對象的值:

Python displays the response in parentheses because it is implicitly interpreting the input as a tuple.

Python将響應顯示在括号中,因為它會将輸入隐式解釋為元組。

There is one peculiarity regarding tuple definition that you should be aware of. There is no ambiguity when defining an empty tuple, nor one with two or more elements. Python knows you are defining a tuple:

關于元組定義,您應該注意一個特質。 定義一個空的元組時,沒有歧義,也沒有兩個或多個元素。 Python知道您正在定義一個元組:

>>> >>>  t t = = ()
()
>>> >>>  typetype (( tt )
)
<class 'tuple'>
<class 'tuple'>
           

But what happens when you try to define a tuple with one item:

但是,當您嘗試用一個項目定義一個元組時會發生什麼:

>>> >>>  t t = = (( 22 )
)
>>> >>>  typetype (( tt )
)
<class 'int'>
<class 'int'>
           

Doh! Since parentheses are also used to define operator precedence in expressions, Python evaluates the expression

(2)

as simply the integer

2

and creates an

int

object. To tell Python that you really want to define a singleton tuple, include a trailing comma (

,

) just before the closing parenthesis:

h! 由于括号也用于定義表達式中的運算符優先級,是以Python将表達式

(2)

視為簡單的整數

2

并建立一個

int

對象。 要告訴Python,您确實要定義一個單例元組,請在右括号前面加上一個逗号(

,

):

You probably won’t need to define a singleton tuple often, but there has to be a way.

您可能不需要經常定義單例元組,但是必須有一種方法。

When you display a singleton tuple, Python includes the comma, to remind you that it’s a tuple:

當顯示單例元組時,Python會包含逗号,以提醒您這是一個元組:

>>> >>>  printprint (( tt )
)
(2,)
(2,)
           

元組配置設定,打包和拆包 (Tuple Assignment, Packing, and Unpacking)

As you have already seen above, a literal tuple containing several items can be assigned to a single object:

如上所示,可以将包含多個項目的文字元組配置設定給單個對象:

When this occurs, it is as though the items in the tuple have been “packed” into the object:

發生這種情況時,就好像元組中的項目已“打包”到對象中:

python中字典清單元組_Python中的清單和元組

Tuple Packing 元組包裝

>>> >>>  t
t
('foo', 'bar', 'baz', 'qux')
('foo', 'bar', 'baz', 'qux')
>>> >>>  tt [[ 00 ]
]
'foo'
'foo'
>>> >>>  tt [[ -- 11 ]
]
'qux'
'qux'
           

If that “packed” object is subsequently assigned to a new tuple, the individual items are “unpacked” into the objects in the tuple:

如果随後将該“打包”對象配置設定給新的元組,則将各個項目“解包”到該元組中的對象中:

python中字典清單元組_Python中的清單和元組

Tuple Unpacking 元組拆包

When unpacking, the number of variables on the left must match the number of values in the tuple:

解壓縮時,左側的變量數必須與元組中的值數比對:

>>> >>>  (( s1s1 , , s2s2 , , s3s3 ) ) = = t
t
Traceback (most recent call last):
  File Traceback (most recent call last):
  File "<pyshell#16>", line "<pyshell#16>" , line 1, in 1 , in <module>
    <module>
    (( s1s1 , , s2s2 , , s3s3 ) ) = = t
t
ValueError: ValueError : too many values to unpack (expected 3)

too many values to unpack (expected 3)

>>> >>>  (( s1s1 , , s2s2 , , s3s3 , , s4s4 , , s5s5 ) ) = = t
t
Traceback (most recent call last):
  File Traceback (most recent call last):
  File "<pyshell#17>", line "<pyshell#17>" , line 1, in 1 , in <module>
    <module>
    (( s1s1 , , s2s2 , , s3s3 , , s4s4 , , s5s5 ) ) = = t
t
ValueError: ValueError : not enough values to unpack (expected 5, got 4)
not enough values to unpack (expected 5, got 4)
           

Packing and unpacking can be combined into one statement to make a compound assignment:

打包和拆包可以合并為一個語句以進行複合配置設定:

Again, the number of elements in the tuple on the left of the assignment must equal the number on the right:

同樣,指派左側的元組中的元素數必須等于右側的數:

>>> >>>  (( s1s1 , , s2s2 , , s3s3 , , s4s4 , , s5s5 ) ) = = (( 'foo''foo' , , 'bar''bar' , , 'baz''baz' , , 'qux''qux' )
)
Traceback (most recent call last):
  File Traceback (most recent call last):
  File "<pyshell#63>", line "<pyshell#63>" , line 1, in 1 , in <module>
    <module>
    (( s1s1 , , s2s2 , , s3s3 , , s4s4 , , s5s5 ) ) = = (( 'foo''foo' , , 'bar''bar' , , 'baz''baz' , , 'qux''qux' )
)
ValueError: ValueError : not enough values to unpack (expected 5, got 4)
not enough values to unpack (expected 5, got 4)
           

In assignments like this and a small handful of other situations, Python allows the parentheses that are usually used for denoting a tuple to be left out:

在這樣的配置設定以及少數其他情況下,Python允許省略通常用于表示元組的括号:

It works the same whether the parentheses are included or not, so if you have any doubt as to whether they’re needed, go ahead and include them.

無論是否包含括号,其工作原理都是一樣的,是以,如果您對是否需要括号存有疑問,請繼續進行添加。

Tuple assignment allows for a curious bit of idiomatic Python. Frequently when programming, you have two variables whose values you need to swap. In most programming languages, it is necessary to store one of the values in a temporary variable while the swap occurs like this:

元組配置設定允許一些慣用的Python。 在程式設計時,經常有兩個變量需要交換其值。 在大多數程式設計語言中,交換發生時,必須将值之一存儲在臨時變量中,如下所示:

>>> >>>  a a = = 'foo'
'foo'
>>> >>>  b b = = 'bar'
'bar'
>>> >>>  aa , , b
b
('foo', 'bar')

('foo', 'bar')

>>># We need to define a temp variable to accomplish the swap.
>>># We need to define a temp variable to accomplish the swap.
>>> >>>  temp temp = = a
a
>>> >>>  a a = = b
b
>>> >>>  b b = = temp

temp

>>> >>>  aa , , b
b
('bar', 'foo')
('bar', 'foo')
           

In Python, the swap can be done with a single tuple assignment:

在Python中,可以通過一個元組配置設定完成交換:

As anyone who has ever had to swap values using a temporary variable knows, being able to do it this way in Python is the pinnacle of modern technological achievement. It will never get better than this.

正如任何曾經使用臨時變量交換值的人都知道的那樣,能夠在Python中以這種方式進行操作是現代技術成就的巅峰之作。 它永遠不會比這更好。

結論 (Conclusion)

This tutorial covered the basic properties of Python lists and tuples, and how to manipulate them. You will use these extensively in your Python programming.

本教程介紹了Python 清單和元組的基本屬性,以及如何操作它們。 您将在Python程式設計中廣泛使用它們。

One of the chief characteristics of a list is that it is ordered. The order of the elements in a list is an intrinsic property of that list and does not change, unless the list itself is modified. (The same is true of tuples, except of course they can’t be modified.)

清單的主要特征之一是它是有序的。 清單中元素的順序是該清單的固有屬性,并且除非更改清單本身,否則不會更改。 (對于元組,同樣如此,但是當然不能對其進行修改。)

The next tutorial will introduce you to the Python dictionary: a composite data type that is unordered. Read on!

下一個教程将向您介紹Python 字典:一種無序的複合資料類型。 繼續閱讀!

翻譯自: https://www.pybloggers.com/2018/07/lists-and-tuples-in-python/

python中字典清單元組