You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何将生成的随机出生日期作为新键添加到列表内的各字典中

实现方案

核心问题点

你现有代码的问题集中在末尾赋值环节:用到了未定义的变量dob_value,且没有将提前生成好的dob列表和ducks列表的元素一一对应,同时你要求新增的键名是date of birth而非代码里写的dob。
另外你写的日期生成逻辑里有两处小细节可按需调整:

  • random.randrange(1, 12)生成的月份范围是1-11,要包含12月可改成random.randrange(1, 13)
  • random.randrange(1, 30)生成的日期范围是1-29,要包含30日可改成random.randrange(1, 31)
  • 函数开头定义的Year变量没有被使用,可以直接删除

修正后的完整代码

ducks =[{'first_name': 'Davey', 'last_name': 'McDuck', 'location': "Rob's Office", 'insane': True, 'followers': 12865, 'following': 120, 
  'weapons': ['wit', 'steely stare', 'devilish good looks'], 'remorse': None}, 
 {'first_name': 'Jim', 'last_name': 'Bob', 'location': 'Turing Lab', 'insane': False, 'followers': 123, 
  'following': 5000, 'weapons': ['squeak'], 'remorse': None}, 
 {'first_name': 'Celest', 'last_name': '', 'location': 'Throne Room', 'insane': True, 'followers': 40189, 'following': 1, 
  'weapons': ['politics', 'dance moves', 'chess grandmaster', 'immortality']}]
import random
dob = []
def dateofbirth(number=1):
    for item in range(number):
        yield random.randrange(1990, 2010), random.randrange(1, 13), random.randrange(1, 31)

dateTimeThatIwant = dateofbirth(3)
for year, month, date in dateTimeThatIwant:
    dob.append([year, month, date])
# 一一对应赋值
for duck, dob_val in zip(ducks, dob):
    duck['date of birth'] = dob_val

# 打印验证结果
print(ducks)

更简洁的写法(无需单独存储dob列表)

如果不需要额外保留dob列表,可以直接边生成出生日期边给字典赋值,代码更精简:

import random
ducks =[{'first_name': 'Davey', 'last_name': 'McDuck', 'location': "Rob's Office", 'insane': True, 'followers': 12865, 'following': 120, 
  'weapons': ['wit', 'steely stare', 'devilish good looks'], 'remorse': None}, 
 {'first_name': 'Jim', 'last_name': 'Bob', 'location': 'Turing Lab', 'insane': False, 'followers': 123, 
  'following': 5000, 'weapons': ['squeak'], 'remorse': None}, 
 {'first_name': 'Celest', 'last_name': '', 'location': 'Throne Room', 'insane': True, 'followers': 40189, 'following': 1, 
  'weapons': ['politics', 'dance moves', 'chess grandmaster', 'immortality']}]

def dateofbirth():
    return random.randrange(1990, 2010), random.randrange(1, 13), random.randrange(1, 31)

for duck in ducks:
    duck['date of birth'] = list(dateofbirth())

print(ducks)

内容的提问来源于stack exchange,提问作者Ali Raza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 01:48:04