【问题标题】:For looping through a Python dictionary用于循环遍历 Python 字典
【发布时间】:2023-10-23 02:05:01
【问题描述】:

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

我的字典:

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

我希望输出是:

123.4
567.8
91011.12

我还想对这些值求和。有没有更简单的方法来使用 SUM 方法而不循环?

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

【问题讨论】:

  • 但是'abc' 的项目不是列表(也不是列表的列表)...我们应该只处理字典中的列表项吗?你试过什么?
  • 见过sum函数吗?
  • sum(x[0] for x in mydict['defg'])
  • 循环没问题,试试看吧。

标签: python dictionary for-loop sum


【解决方案1】:

好的,我想我明白了。感谢 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

【讨论】:

    【解决方案2】:

    最后,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))
    

    【讨论】:

      【解决方案3】:

      您可以使用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
      

      【讨论】:

        最近更新 更多