【问题标题】:Store the result of for loop iteration in a dictionary将 for 循环迭代的结果存储在字典中
【发布时间】:2019-12-31 10:37:15
【问题描述】:

我是 Python 新手,从一些教程开始学习它。

我有一个 for 循环,它将输出存储在字典中。在代码的末尾,字典正在更新,仅存储最后一次 for 循环迭代的结果。这是for循环的基本功能,没问题。

我只想拥有从 for 循环迭代的不同字典中的所有值。

下面是我的代码

from collections import defaultdict
import glob
from PIL import Image
from collections import Counter

for file in glob.glob('C:/Users/TestCase/Downloads/test/*'): 

    by_color = defaultdict(int)
    im = Image.open(file)
    for pixel in im.getdata():
        by_color[pixel] += 1
    by_color

    # Update the value of each key in a dictionary to 1
    d = {x: 1 for x in by_color}
    # Print the updated dictionary

    check = dict(d)

    print(check) // Print the results from the for loop

 print(check) // Prints only the last iteration result of for loop

编辑:

从下面发布的答案中,我得到了一个包含所有键和值的字典列表。

实际输出:

[{(0, 255, 255): 1, (33, 44, 177): 1, (150, 0, 0): 1, (255, 0, 255): 1, (147, 253, 194): 1, (64, 0, 64): 1, {(0, 255, 255): 1, (33, 44, 177): 1, (150, 0, 0): 1, (96, 69, 143): 1, (255, 0, 255): 1}]

期望的输出:

[{(0, 255, 255): 2, (33, 44, 177): 2, (150, 0, 0): 2, (96, 69, 143): 1, (255, 0, 255): 2, (147, 253, 194): 1, (64, 0, 64): 1}]

【问题讨论】:

  • 你已经更新了同一个键的值

标签: python python-3.x dictionary for-loop


【解决方案1】:

您可以创建一个列表来存储您的字典并在每次迭代结束时添加字典。它看起来像这样:

from collections import defaultdict
import glob
from PIL import Image
from collections import Counter

my_dicts = []

for file in glob.glob('C:/Users/TestCase/Downloads/test/*'): 

    by_color = defaultdict(int)
    im = Image.open(file)
    for pixel in im.getdata():
        by_color[pixel] += 1
    by_color

    # Update the value of each key in a dictionary to 1
    d = {x: 1 for x in by_color}
    # Print the updated dictionary

    check = dict(d)

    print(check) # Print the results from the for loop

    my_dicts.append(check)

print(my_dicts) # Prints the dictionaries stored in a list

编辑:回答您的其他问题,您可以使用计数器来实现您想要做的事情:

from collections import defaultdictfrom
import glob
from PIL import Image
from collections import Counter

my_dicts = []

for file in glob.glob('C:/Users/TestCase/Downloads/test/*'): 

    by_color = defaultdict(int)
    im = Image.open(file)
    for pixel in im.getdata():
        by_color[pixel] += 1
    by_color

    # Update the value of each key in a dictionary to 1
    d = {x: 1 for x in by_color}
    # Print the updated dictionary

    check = dict(d)

    print(check) # Print the results from the for loop

    my_dicts.append(check)

my_counters = [Counter(d) for d in my_dicts]

res = Counter()
for c in my_counters:
    res += c
output = dict(res)

【讨论】:

  • 感谢您的快速响应,这看起来不错。我可以对不同字典中相同键的附加语句中的值求和吗?
  • 您能否提供所需输出的示例?您只想要一个包含每个循环值的字典吗?
  • 我刚刚修改了您回答中的问题。我添加了实际和期望的结果
  • 非常感谢 Silveris 的快速响应
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-04
  • 2021-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-03
相关资源
最近更新 更多