灰帽python之旅_Python收藏之旅

灰帽python之旅

In this tutorial, I'm going to cover several different types of collections in Python.

在本教程中,我将介绍Python中的几种不同类型的集合。

Before we get started, let's define what a collection is. A collection is similar to a basket that you can add and remove items from. In some cases, they are the same types of items, and in others they are different. Basically, it's a storage construct that allows you to collect things.

在开始之前,让我们定义一个集合。 集合类似于您可以在其中添加和删除项目的购物篮。 在某些情况下,它们是相同类型的项目,而在另一些情况下,它们是不同的。 基本上,它是一种存储结构,可让您收集东西。

For example, you might have a car type. You create several instances of the car and want some way to group all of those cars together and access them easily. This is the perfect scenario for a collection.

例如,您可能有汽车类型。 您创建了汽车的多个实例,并希望通过某种方式将所有这些汽车分组在一起并轻松访问它们。 这是收集的理想方案。

The collection will survive in memory. You don't need to build the collection or create any type of scaffolding. All of that is provided for free. Just create a collection instance and start adding your cars. When you're ready, you can pull them out by name or by index (position within the collection).

该集合将保留在内存中。 您不需要构建集合或创建任何类型的脚手架。 所有这些都是免费提供的。 只需创建一个集合实例并开始添加您的汽车即可。 准备就绪后,可以按名称或按索引(集合中的位置)将其拉出。

Python offers several built-in types that fall under a vague category called collections. While there isn't a formal type called collection in Python, there are lists, mappings, and sets.

Python提供了几种内置类型,它们属于模糊的类别(称为集合)。 虽然在Python中没有一个正式的类型称为collection ,但是有列表,映射和集合。

In this tutorial, we're going cover the following types:

在本教程中,我们将介绍以下类型:

  • lists

    清单
  • strings

  • dictionaries

    词典
  • sets

清单 (List)

Lists in Python are a built-in type called a sequence. List are mutable and allow you to add items of the same type or different types, making them very versatile constructs. Python lists are similar to arrays in other languages.

Python中的列表是一种称为序列的内置类型。 列表是可变的,允许您添加相同或不同类型的项目,使它们成为非常通用的构造。 Python列表类似于其他语言中的数组。

Python lists do allow you to have non-unique elements.

Python列表确实允许您具有非唯一元素。

The following is an example of creating a list and adding items to it:

以下是创建列表并向其中添加项目的示例:

alist = ["item1", "item2", 4]

Notice the list is heterogenous, containing string and numeric types.

请注意,列表是异构的,包含字符串和数字类型。

To retrieve an item from a list, simply reference the item's index. Python lists are zero indexed. If I want the last item, which is position 3, I need to use an index of 2:

要从列表中检索项目,只需引用该项目的索引即可。 Python列表的索引为零。 如果我想要最后一项,即位置3,则需要使用2的索引:

alist[2]
> 4

The number 4 is returned. When referencing a list item, just subtract one from its position to get the correct index value.

返回数字4。 当引用一个列表项时,只需从其位置减去一个即可获得正确的索引值。

Checking the length of a list can be done using the len command:

可以使用len命令检查列表的长度:

len(alist))
> 3

To add more items to the list, use the append() function:

要将更多项目添加到列表中,请使用append()函数:

alist.append(False)
len(alist)
> 4

We've increased the list by one and added a different type — the boolean. The list doesn't complain at all.

我们将列表增加了一个,并添加了另一种类型-布尔值。 该列表完全没有抱怨。

We can delete elements by calling remove():

我们可以通过调用remove()来删除元素:

alist.remove("item2")

remove() doesn't return a value. The list will be updated and now contains three items:

remove()不返回值。 该列表将被更新,现在包含三个项目:

['item1', 4, False]

There are a couple of other ways to get items out of a list. We saw how to access an item using its index. If I access index 2, I'll get item 3:

还有几种其他方法可以将项目从列表中删除。 我们看到了如何使用其索引访问项目。 如果我访问索引2,则将获得项目3:

thevalue = alist[2]
print(thevalue)
> False

The above code will supply us with a copy of the item. That item is still in the list. The overall list count isn't affected.

上面的代码将为我们提供该物品的副本。 该项目仍在列表中。 列表总数不受影响。

However, if we use pop(), we get the item, but it is also removed from the list:

但是,如果我们使用pop() ,则会得到该项目,但也会从列表中将其删除:

thevalue = alist.pop(1)
print(thevalue)
> 4
print("after pop", alist)
> ['item1', False]

Lists can also be sorted. If I have the following list of strings:

列表也可以排序。 如果我有以下字符串列表:

alpha = ["z", "b", "a", "c"]

you can sort it using the sort() command:

您可以使用sort()命令对其进行sort()

alpha.sort()

sort() doesn't return a value. However, alpha is now sorted. You can see this by printing the list:

sort()不返回值。 但是, alpha已排序。 您可以通过打印列表来查看:

print(alpha)

Elements can be reversed just as easily by calling reverse():

可以通过调用reverse()轻松地反转元素:

alpha.reverse()

reverse() also doesn't return a value, and will reverse the current list.

reverse()也不会返回任何值,而是会反转当前列表。

字符串是列表吗? (Is a String a List?)

Strings have some similarities to lists. However, strings are immutable, while lists are mutable.

字符串与列表有一些相似之处。 但是,字符串是不可变的,而列表是可变的。

Strings are index based like a list. You can also get a count of characters in a string, just like you can get a count of items in a list.

字符串像列表一样基于索引。 您还可以获取字符串中的字符数,就像可以获取列表中的项数一样。

For example:

例如:

mystring = "The quick brown fox." 
print(len(mystring)) 
> 20
print(mystring[4])
> q

Unlike a list, you can't add another character by appending it. You also can't update a specific element within the string.

与列表不同,您不能通过附加字符来添加其他字符。 您也无法更新字符串中的特定元素。

Notice what happens if we try to assign a character to a specific position within the string:

注意如果尝试将字符分配给字符串中的特定位置会发生什么:

mystring[4] = 'z'
> TypeError: 'str' object does not support item assignment

This is where the immutable part of strings comes into play.

这是字符串不变部分起作用的地方。

Depending on the string, we can convert a string into a list. Take our mystring variable from above. If we split() the string, it will default to splitting on spaces:

根据字符串,我们可以将字符串转换为列表。 从上面获取我们的mystring变量。 如果我们对字符串进行split() ,则默认为在空格处分割:

stringlist = mystring.split()
stringlist
>['The', 'quick', 'brown', 'fox.']
type(stringlist)
><class 'list'>

Each word in the string becomes an element in a list. We can also see the type is clearly a list.

字符串中的每个单词都成为列表中的一个元素。 我们还可以看到类型显然是一个列表。

If the string has no spaces, we can still split it. But what will the result be? Let's check it:

如果字符串没有空格,我们仍然可以拆分它。 但是结果是什么呢? 让我们检查一下:

mystring2 = "Thequickbrownfox." 
stringlist2 = mystring2.split()
stringlist2
type(stringlist2)
>['Thequickbrownfox.']
><class 'list'>

We still get a list but this time with only one element. Ultimately, there isn't much utility to splitting a string in this case.

我们仍然会得到一个列表,但是这次只有一个元素。 最终,在这种情况下,拆分字符串的实用性很小。

对应 (Mappings)

Mappings are another built-in type. The only mapping available in Python is the dictionary. Dictionaries are key/value based. Unlike a list, which is index based, we don't access dictionary values using indexes. Instead, we access values using keys.

映射是另一种内置类型。 Python中唯一可用的映射是字典。 字典是基于键/值的。 与基于索引的列表不同,我们不使用索引访问字典值。 相反,我们使用键访问值。

Creating a dictionary is similar to creating a list with the exception of adding key/value pairs rather than single items. Here's an example:

创建字典类似于创建列表,只是添加键/值对而不是单个项。 这是一个例子:

mydictionary = {"item1":45, "item2":76, "item3":145}

Each key/value is separated by a colon. The first part is the key and the second part is the value. In the first item, item1 is the key and 45 is the value. Also, notice we use braces instead of brackets to enclose our items.

每个键/值都用冒号分隔。 第一部分是键,第二部分是值。 在第一项中, item1是键,而45是值。 另外,请注意,我们使用花括号而不是括号来包围我们的物品。

When getting items from a dictionary, we think in terms of the key, since accessing via index isn't possible. If we want item2, we use:

从字典中获取项目时,我们会考虑键,因为无法通过索引访问。 如果我们需要item2 ,则使用:

mydictionary["item2"]
> 76

We can check a dictionary's length, in the same way we check a list's length:

我们可以检查字典的长度,就像检查列表的长度一样:

len(mydictionary)
> 3

To update item2, we use do the following:

要更新item2 ,我们使用以下操作:

mydictionary["item2"] = 100

Adding an item is the same syntax as updating:

添加项目与更新的语法相同:

mydictionary["item62"] = 433

item62 now exists in the dictionary, and the total count has increased by one.

现在,字典中存在item62 ,并且总数增加了1。

Dictionary items can be deleted by referencing a specific key:

可以通过引用特定键来删除字典项:

del mydictionary["item2"]

item2 is now removed. As you can see, dictionary operations are fairly straight forward.

现在已删除item2 。 如您所见,字典操作相当简单。

As mentioned earlier, dictionaries have key/value pairs. If you'd like to access only keys, you can do this:

如前所述,字典具有键/值对。 如果您只想访问密钥,则可以执行以下操作:

mydictionary.keys()
> dict_keys(['item3', 'item1', 'item62'])

Values are accessed the same way:

值的访问方式相同:

mydictionary.values()
> dict_values([145, 45, 433])

套装 (Sets)

Sets are unordered collections that can't have duplicate elements. Sets can't be sorted. The sort() method isn't available for sets.

集是无序集合,不能有重复的元素。 集无法排序。 sort()方法不适用于集合。

In comparison to lists, sets can check for the existence of an element faster than lists.

与列表相比,集合可以比列表更快地检查元素的存在。

To create a set, simply do the following:

要创建集合,只需执行以下操作:

myset = {3,4,5,1}

Or use the set method and supply an existing structure. For example:

或使用set方法并提供现有结构。 例如:

mylist = [0,1,5,4,3,7,6,6]
myset = set(mylist)
>{0, 1, 3, 4, 5, 6, 7}

Since sets can only contain unique items, notice that one of the duplicate 6s was removed. Using set() is great for creating a unique collection of items from existing data.

由于集合只能包含唯一项,因此请注意,删除了重复的6 s之一。 使用set()非常适合根据现有数据创建项目的唯一集合。

If I try to add the 6 back, it doesn't have any effect:

如果我尝试将6重新添加回去,则没有任何效果:

myset.add(6)
>{0, 1, 3, 4, 5, 6, 7}

To remove an element from a set, you can call the remove() method:

要从集合中删除元素,可以调用remove()方法:

myset.remove(4)

4 is no longer in myset.

4已不再是我的myset

Sets also don't support indexing. Trying to access an element within a set throws and error:

集也不支持索引。 尝试访问集合中的元素引发和错误:

myset[2]
>TypeError: 'set' object does not support indexing

Sets have some methods unique to them. If you're familiar with the mathematical operations of sets (difference, intersection, and union), these methods will be well known to you.

集具有一些独特的方法。 如果您熟悉集合的数学运算(差异,交集和并集),那么这些方法将为您所熟知。

We'll start with difference(). Suppose I have these two sets:

我们将从difference()开始。 假设我有这两套:

set1 = {1,3,6,7}
set2 = {1,3,6,8,10}

Using set1, the difference with set2 is 7. 7 is in set1 but not in set2. In Python, this looks like the following:

使用set1 ,与set2的差为77set1但不在set2 。 在Python中,如下所示:

set1.difference(set2)
>{7}

To go the other way:

换种方式:

set2.difference(set1)
>{8, 10}

What about finding what is common in two sets:

如何找出两组中的共同点:

set1.intersection(set2)
>{1, 3, 6}

And finally, combine both sets to create a new set:

最后,将这两个集合合并以创建一个新集合:

set3 = set1.union(set2)
>{1, 3, 6, 7, 8, 10}

The union set includes all items from both sets.

联合集包括两个集合中的所有项目。

摘要 (Summary)

We've gone through Python lists, strings (although not a sequence), dictionaries and sets. We've looked at specific operations and unique abilities of all. I hope this tutorial has further enhanced your knowledge of collections in Python.

我们已经遍历了Python列表,字符串(虽然不是序列),字典和集合。 我们研究了所有人的特定操作和独特能力。 我希望本教程可以进一步增强您对Python集合的了解。

翻译自: https://www.sitepoint.com/a-tour-of-python-collections/

灰帽python之旅

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值