繁体   English   中英

循环遍历 Python 字典

[英]For looping through a Python dictionary

我正在尝试遍历字典并打印每一行的第一个浮点值,但我不知道如何选择我只想要这些值。

我的字典:

{'abc': 123123, 'defg': [
    ['123.4', '10'],
    ['567.8', '10'],
    ['91011.12', '10']
]}

我希望输出是:

123.4
567.8
91011.12

我也想总结这些值。 使用 SUM 方法是否有更简单的方法来做到这一点而无需循环?

谢谢您的帮助! 我真的很迷茫。

好的,我想我明白了。 感谢 Ajax1234 和 Jerfov2 的提示!

s = {'abc': 123123, 'defg': [
['123.4', '10'],
['567.8', '10'],
['91011.12', '10']
]}

For 循环和打印:

for x in s['defg']:
    print(x[0])

输出:

123.4
567.8
91011.12

和 for 循环求和:

summed = 0
for x in s['defg']:
    summed = summed + float(x[0])
print("%.2f" % summed)

输出:

91702.32

最后,Python 中的任何函数式方法都只是语法糖,以下是我在非函数式方式下的 2 美分:

import ast
import itertools

s = {'abc': 123123, 'defg': [
    ['123.4', '10'],
    ['567.8', '10'],
    ['91011.12', '10']
]}

def str_is_float(value):
    if isinstance(value, str):
        value = ast.literal_eval(value)
    if isinstance(value, float):
        return True
    else:
        return False

def get_floats(d):
    for k, v in d.items():
        if isinstance(v, list):
            for n in itertools.chain.from_iterable(v):
                if str_is_float(n):
                    yield float(n) 
        elif str_is_float(v):
            yield float(v)

floats = list(get_floats(s))

# Print all the floats
print(floats) 
# sum the floats
print(sum(x for x in floats))

您可以使用reduce来获得更多功能的解决方案:

import re
import itertools
from functools import reduce
s = {'abc': 123123, 'defg': [
 ['123.4', '10'],
['567.8', '10'],
['91011.12', '10']
]}
new_s = list(itertools.chain(*[[float(c) for c in itertools.chain(*b) if re.findall('^\d+\.\d+$', c)] for a, b in s.items() if isinstance(b, list)]))
print(new_s)
print(reduce(lambda x, y:x+y, new_s))

输出:

[123.4, 567.8, 91011.12]
91702.32

暂无
暂无

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

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