python - 将 for 循环迭代的结果存储在字典中
问题描述
我是 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}]
解决方案
您可以创建一个列表来存储您的字典并在每次迭代结束时添加字典。它看起来像这样:
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)
推荐阅读
- excel - MS Access 导出子表单 VBA
- reactjs - 在 React 中调用下一个 Flicking Carousel
- python - 无法从 google-colaboratory 打开 google-storage 中的文件
- mysql - Mysql查询 - 返回两个日期范围相交的日期
- xml - 在 XPath 中选择相反的条件?
- python - 正则表达式简单域
- java - 为什么没有执行 SQL 查询并且没有使用 postgresql 创建表 spring boot crud rest api 项目?
- python - python-onvif-zeep | ptz.stop() 抛出错误 | onvif.exceptions.ONVIFError:未知错误:操作不支持
- reactjs - 所有环境变量都必须以 REACT_APP 为前缀才能与纱线一起使用吗?
- reporting-services - Dynamics 365 Online 中报表的转义超时限制