简体   繁体   English

Python:这是什么类型的对象?

[英]Python: what type of object is here?

I'm struggling with the book LPTHW http://learnpythonthehardway.org/book/ex39.html 我在LPTHW这本书( http://learnpythonthehardway.org/book/ex39.html)上挣扎

Here is the code: 这是代码:

def new(num_buckets=256):
    """Initializes a Map with the given number of buckets."""
    aMap = []
    for i in range(0, num_buckets):
        aMap.append([])
    return aMap

def hash_key(aMap, key):
    """Given a key this will create a number and then convert it to
    an index for the aMap's buckets."""
    return hash(key) % len(aMap)

def get_bucket(aMap, key):
    """Given a key, find the bucket where it would go."""
    bucket_id = hash_key(aMap, key)
    return aMap[bucket_id]

def get_slot(aMap, key, default=None):
    bucket = get_bucket(aMap, key)
    for i, kv in enumerate(bucket):
        k, v = kv
        if key == k:
            return i, k, v
    return -1, key, default

What does kv means in get_slot ? kvget_slot是什么意思? What type of object is this? 这是什么类型的物体? Why the code below does not work? 为什么下面的代码不起作用? I get TypeError: 'int' object is not iterable 我收到TypeError: 'int' object is not iterable

for i, kv in enumerate([1,2,3,4,5]):
    k, v = kv
    print(kv)

Update: It was a good idea to check one more time how enumerate works https://docs.python.org/2/library/functions.html#enumerate . 更新:最好再检查一次enumerate工作方式https://docs.python.org/2/library/functions.html#enumerate Thank everyone for the answers. 谢谢大家的回答。

kv is assigned one of the values in the sequence that get_bucket(aMap, key) produces; kv分配了get_bucket(aMap, key)产生的序列中的值之一; each iteration over enumerate() produces another one of those values (together with an integer counter, assigned to i in the example code). enumerate()每次迭代都会生成这些值中的另一个(连同在示例代码中分配给i的整数计数器)。 Apparently each one of those objects it itself an iterable with two elements. 显然,这些对象中的每个对象本身都可以由两个元素迭代。

Your attempt produced a list with just integers, which are not themselves iterable, which is why the k, v = kv assignment fails. 您的尝试产生了一个仅包含整数的列表,这些整数本身不可迭代,这就是为什么k, v = kv分配失败的原因。 Try this instead: 尝试以下方法:

for i, kv in enumerate([('foo', 1), ('bar', 2), ('baz', 3)]):
    k, v = kv

This iterates over a sequence of (str, int) tuples, so the k, v = kv iterable unpacking works. 这遍历了(str, int)元组的序列,因此k, v = kv可迭代的拆包工作。

In general, all enumerate() does is add a sequence number; 通常,所有enumerate()所做的只是添加一个序列号。 the default is to start at 0. So for each iteration in a for loop, enumerate(something) produces (counter, value_from_something) . 默认是0,所以开始的每次迭代中for循环, enumerate(something)生产(counter, value_from_something) That value_from_something is itself still just a Python object, which can support all sorts of operations. value_from_something本身仍然只是一个Python对象,它可以支持各种操作。

You can see from the new() function in the same sample, that the code deals with a list of lists: 您可以从同一示例的new()函数中看到,该代码处理的是列表列表:

def new(num_buckets=256):
    """Initializes a Map with the given number of buckets."""
    aMap = []
    for i in range(0, num_buckets):
        aMap.append([])
    return aMap

so aMap is a list containing other lists. 因此aMap是一个包含其他列表的列表。 The code refers to each of those lists as buckets . 该代码将每个列表称为存储桶 The set() function shows that those buckets contain tuples with two values, the key and the value: set()函数表明,这些存储桶包含具有两个值的元组 ,即键和值:

else:
    # the key does not, append to create it
    bucket.append((key, value))

The get_slot() function handles one of those buckets, which contains 0 or more (key, value) pairs (and all the keys have hashed to the same bucket). get_slot()函数处理这些存储桶中的一个,其中包含0个或多个(key, value)对(并且所有键都已散列到同一存储桶)。

enumerate() returns an iterator of tuples. enumerate()返回一个元组的迭代器 Each tuple is an index and a value. 每个元组都是一个索引和一个值。 For example, if you say enumerate([2, 3, 4]) , you will get (0, 2) , (1, 3) , and (2, 4) . 例如,如果您说enumerate([2, 3, 4]) ,您将得到(0, 2)(1, 3)(2, 4) Since you use for i, kv in enumerate(...) , the first iteration for example will have i == 0 and kv == 2 . 因为您for i, kv in enumerate(...)使用for i, kv in enumerate(...) ,所以例如第一次迭代将具有i == 0kv == 2 You then say k, v = kv , but kv is only one integer. 然后k, v = kv您说k, v = kv ,但kv只是一个整数。 It is not a tuple or a list etc. so you can't split it into two variables. 它不是元组或列表等,因此您不能将其分为两个变量。 If you were to say enumerate([(2, 3), (4, 5), (6, 7]) instead, you could do that because i would be 0 when kv is (2, 3) . kv could be split into two variables so that k is 2 and v is 3 . 如果你说enumerate([(2, 3), (4, 5), (6, 7])代替,就可以做到这一点,因为i将是0kv(2, 3) kv可以再分分为两个变量,因此k2v3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM