【问题标题】:how to print just the values of the tuple element values in the dictionary while iterating through it如何在遍历字典时仅打印字典中元组元素值的值
【发布时间】:2018-02-11 05:05:49
【问题描述】:
d = {'k1':1,'k2':[(2,4),(6,8),(10,12)],'k3':3}

for (a,b) in d.values():
    print (a)
    print (b)

当我尝试这个时,它会说

TypeError                                 Traceback (most recent call last)
 <ipython-input-49-81a0566d1778> in <module>()
  ----> 1 for (a,b) in d.values():
  2     print (b)
  3     print (a)

 TypeError: 'int' object is not iterable

我只想将输出打印为

2

4

6

8

10

12

【问题讨论】:

  • 并非您示例中的所有dict 值都是tuple,这就是您收到此错误的原因。
  • @bro-grammer。首先,很棒的用户名。其次,nitpick,但不是每个值都是包含元组的列表,或者包含双元素可迭代的可迭代。

标签: python dictionary iteration


【解决方案1】:

因为您的字典既包含元组列表(您想要展平),也包含整数:

d = {'k1':1,'k2':[(2,4),(6,8),(10,12)],'k3':3}

在展平列表之前,您必须先检查类型,然后遍历其内容:

for (key, value) in d.items():
    if type(value) is list:
        # flatten the list of tuples into a list of ints
        # by applying `itertools.chain` on the unpacked (*) list
        # of tuples
        flattened = itertools.chain(*d[key])
        for num in flattened:
            print(num)

注意:要扁平化您的列表,您需要导入 itertools,并且在 Python 2.7+ 和 Python 3 中解包工作。

【讨论】:

    【解决方案2】:
    # for key,val in d.items(): # python 3 version
    for key,val in d.iteritems(): # go through all of key, values of d
        if isinstance(val, list): # check if they are a list/array
            for tup in val: # if they are, go through all of them
                if isinstance(tup, tuple):
                    for num in tup: # don't assume they are all 2 number tuples
                        print("{0}\n".format(num)) # print each with an extra new line
    

    您假设所有 dict 值都是元组。尽量少假设它们,并确保检查它们的类型。通过确保它是一个列表,您就可以知道您可以遍历该列表。之后确保列表中的所有元素都是元组,然后遍历元组中的所有数字并打印(这也允许您打印具有超过 2 个数字的元组。

    【讨论】:

      猜你喜欢
      • 2018-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 2019-10-21
      • 2015-07-22
      • 1970-01-01
      相关资源
      最近更新 更多