【问题标题】:List of dictionary within dictionary using for loop使用for循环的字典中的字典列表
【发布时间】:2017-04-05 20:51:55
【问题描述】:

我正在 python 中为 xlsxwriter 创建随机颜色

import random
point = []
dict1 = {}
for row_count in range(3):

    fill = {
    "color": '#' + ''.join([random.choice('0123456789ABCDEF') for x in range(6)]),
}
    dict1['fill'] = fill
    print fill
    point.append(dict1)
print point

预期输出

[{'fill': {'color': '#8C4372'}}, {'fill': {'color': '#5EF546'}}, {'fill': {'color': '#386CF4'}}]

实际输出

{'color': '#8C4372'}
{'color': '#5EF546'}
{'color': '#386CF4'}
[{'fill': {'color': '#386CF4'}}, {'fill': {'color': '#386CF4'}}, {'fill': {'color': '#386CF4'}}]

如何解决。

提前致谢

【问题讨论】:

  • 它看起来像我眼中的预期输出......有什么问题?
  • 如果你去掉`打印填充`,你会得到预期的输出
  • dict1 = {}移动到for循环中
  • FWIW,我可能会做类似from random import randrange;[{'fill':{'color':'#%06X'%randrange(0x1000000)}}for _ in'...'] 的事情,但这只是我。 :)

标签: python python-2.7 dictionary for-loop


【解决方案1】:

您可以使用 列表推导 表达式实现相同的效果:

[{'file': {'color': ''.join([random.choice('0123456789ABCDEF') for x in range(6)])}} for row_count in range(3)]

【讨论】:

    【解决方案2】:

    您对所有填充对象使用相同的字典 dict1,每次将其添加到点时创建一个新的:

    import random
    point = []
    for row_count in range(3):
        fill = {
            "color": '#' + ''.join([random.choice('0123456789ABCDEF') for x in range(6)]),
        }
        point.append({"fill": fill})
    

    【讨论】:

      【解决方案3】:

      问题是您正在重复使用dict1 并重新分配“填充”键。由于它在所有条目之间共享,因此所有条目都将获得新值。改为这样做:

      import random
      
      def random_color():
          return '#' + ''.join(random.choice('0123456789ABCDEF') for x in range(6))
      
      rows = []
      for _ in range(3):
          fill = {"color": random_color()}
          rows.append({"fill": fill})
      
      print rows
      

      或者使用列表推导:

      rows = [{'fill': {'color': random_color()}} for _ in range(3)]
      

      【讨论】:

        【解决方案4】:

        由于颜色范围从 0x000000 到 0xFFFFFF,您可以使用 randint() 生成随机颜色:

        from random import randint
        
        '#%6X' % randint(0x000000, 0xFFFFFF)
        

        【讨论】:

          猜你喜欢
          • 2022-11-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-10-11
          • 2021-07-06
          • 2018-02-16
          • 1970-01-01
          • 2015-10-30
          相关资源
          最近更新 更多