迭代Python中的dict或列表

时间:2012-09-07 21:25:39

标签: python list dictionary loops

刚刚写了一些讨厌的代码,迭代Python中的dictlist。我觉得这不是最好的方法。

问题在于,为了迭代dict,这就是惯例:

for key in dict_object:
    dict_object[key] = 1

但是如果在列表上完成相同的操作,则按键修改对象属性不起作用:

# Throws an error because the value of key is the property value, not 
#     the list index:

for key in list_object:
    list_object[key] = 1 

我解决这个问题的方法是编写这个讨厌的代码:

if isinstance(obj, dict):
    for key in obj:
        do_loop_contents(obj, key)
elif isinstance(obj, list):
    for i in xrange(0, len(obj)):
        do_loop_contents(obj, i)

def do_loop_contents(obj, key):
    obj[key] = 1

有更好的方法吗?

谢谢!

5 个答案:

答案 0 :(得分:14)

我永远不需要这样做。但如果我这样做,我可能会做这样的事情:

seq_iter = x if isinstance(x, dict) else xrange(len(x))

例如,以函数形式:

>>> def seq_iter(obj):
...     return obj if isinstance(obj, dict) else xrange(len(obj))
... 
>>> x = [1,2,3]
>>> for i in seq_iter(x):
...     x[i] = 99
... 
>>> x
[99, 99, 99]
>>> 
>>> x = {1: 2, 2:3, 3:4}
>>> for i in seq_iter(x):
...     x[i] = 99
... 
>>> x
{1: 99, 2: 99, 3: 99}

答案 1 :(得分:6)

这是正确的方法,但如果由于某种原因你需要以同样的方式处理这两个对象,你可以创建一个无论如何都会返回索引/键的迭代:

def common_iterable(obj):
    if isinstance(obj, dict):
        return obj
    else:
        return (index for index, value in enumerate(obj))

哪种行为符合您的要求:

>>> d = {'a': 10, 'b': 20}
>>> l = [1,2,3,4]
>>> for index in common_iterable(d):
    d[index] = 0

>>> d
{'a': 0, 'b': 0}
>>> for index in common_iterable(l):
    l[index] = 0

>>> l
[0, 0, 0, 0]

或者可能更有效率,使用发电机:

def common_iterable(obj):
    if isinstance(obj, dict):
        for key in obj:
            yield key
    else:
        for index, value in enumerate(obj):
            yield index

答案 2 :(得分:2)

要成为pythonic和ducktype-y,并且还要遵循“请求宽恕而不是许可”,你可以做类似的事情:

try:
    iterator = obj.iteritems()
except AttributeError:
    iterator = enumerate(obj)
for reference, value in iterator:
    do_loop_contents(obj, reference)

虽然你需要的只是键/索引:

try:
    references = obj.keys()
except AttributeError:
    references = range(len(obj))
for reference in references:
    do_loop_contents(obj, reference)

或作为一项功能:

def reference_and_value_iterator(iterable):
    try:
        return iterable.iteritems()
    except AttributeError:
        return enumerate(iterable)

for reference, value in reference_and_value_iterator(obj):
    do_loop_contents(obj, reference)

或仅供参考:

def references(iterable):
    try:
        return iterable.keys()
    except AttributeError:
        return range(len(iterable))

for reference in references(obj):
    do_loop_contents(obj, reference)

答案 3 :(得分:1)

test_list = [2, 3, 4]
for i, entry in enumerate(test_list):
    test_list[i] = entry * 2
print(test_list)  # Gives: [4, 6, 8]

但你可能想要列表理解:

test_list = [2, 3, 4]
test_list = [entry * 2 for entry in test_list]
print(test_list)  # Gives: [4, 6, 8]

答案 4 :(得分:1)

您可能只想拥有不同的代码,具体取决于您尝试更改的对象是dict还是列表。

if type(object)==type([]):
    for key in range(len(object)):
        object[key]=1
elif type(object)==type({}): #use 'else' if you know that object will be a dict if not a list
    for key in object:
        object[key]=1