如何遍历此字典并访问这些项?

时间:2019-06-20 13:45:49

标签: python data-structures iteration

(defaultdict(None, {0: [((u'blood', u'test'), (2148, 'lab'), (1, 2), ''), ((u'crocin',), (u'47444.0', 'med'), (0,), '')], 1: [((u'back', u'pain'), (98, 'hc'), (0, 1), '')]}), [u'crocin blood test', u'back pain'], ['crocin blood test', 'back pain'])

我想遍历此字典并仅访问包含数字,字符串对的元组,例如2148,lab和47444.0,med和98,hc 我如何运行循环来访问这些项目? 这些项目的数量可以是可变的。 我有一个功能,可以将输入的“番红花血液测试。背痛”转换为上述字典。

1 个答案:

答案 0 :(得分:0)

这是你的追求吗?

dd = defaultdict(None, {0: [((u'blood', u'test'), (2148, 'lab'), (1, 2), ''), ((u'crocin',), (u'47444.0', 'med'), (0,), '')], 
                        1: [((u'back', u'pain'), (98, 'hc'), (0, 1), '')]})

for list_of_tuples in dd.values():
    for tuples in list_of_tuples:
        for tup in tuples:
            if len(tup) == 2:
                # Check if the 1st tuple element is a string
                if type(tup[1]) is not str:
                    continue

                # Check if the 0th tuple element is a number
                if type(tup[0]) is int:
                    is_number = True
                else:
                    try:
                        float(tup[0])
                        is_number = True
                    except ValueError:
                        is_number = False
                if is_number:
                    print("number-string pair found:", tup)

输出:

number-string pair found: (2148, 'lab')
number-string pair found: ('47444.0', 'med')
number-string pair found: (98, 'hc')

由于实际上已经存储了一些数字和字符串,因此您必须使用intfloat检查它们是否是有效数字。


重构以清理逻辑:

for list_of_tuples in dd.values():
    for tuples in list_of_tuples:
        for tup in tuples:
            if len(tup) == 2 and isinstance(tup[1], str):
                try:
                    _ = float(tup[0])
                    print("number-string pair found:", tup)
                except ValueError:
                    pass

实际上,可能不需要条件语句中的and isinstance(tup[1], str)


可以迭代的生成器:

def f(d):
    for list_of_tuples in dd.values():
        for tuples in list_of_tuples:
            for tup in tuples:
                if len(tup) == 2 and isinstance(tup[1], str):
                    try:
                        _ = float(tup[0])
                        yield tup
                    except ValueError:
                        pass

for thing in f(dd):
    print(thing)