简体   繁体   English

循环遍历 Python 字典

[英]For looping through a Python dictionary

I'm trying to for loop through a dictionary and print the first float value of every row but I have no idea how to choose that I want just those values.我正在尝试遍历字典并打印每一行的第一个浮点值,但我不知道如何选择我只想要这些值。

My dictionary:我的字典:

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

I want the output to be:我希望输出是:

123.4
567.8
91011.12

Also I want to sum those values.我也想总结这些值。 Is there easier way to do that with SUM method without looping?使用 SUM 方法是否有更简单的方法来做到这一点而无需循环?

Thanks for the help!谢谢您的帮助! I'm really lost with this.我真的很迷茫。

Ok I think I got it.好的,我想我明白了。 Thanks to Ajax1234 and Jerfov2 for tips!感谢 Ajax1234 和 Jerfov2 的提示!

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

For loop and print: For 循环和打印:

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

Outputs:输出:

123.4
567.8
91011.12

And the summing with for loop:和 for 循环求和:

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

Outputs:输出:

91702.32

At the very end any functional approach in Python is just syntactic sugar, here are my 2 cents in a non-functional fashion:最后,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))

You can use reduce for a more functional solution:您可以使用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))

Output:输出:

[123.4, 567.8, 91011.12]
91702.32

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

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