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

Python中如何正确使用append方法向对应列表添加随机值

问题根源

你当前代码无法正常运行的核心原因是stats列表中存储的是属性名的字符串值,而非你预先定义的6个空列表对象。循环遍历stats时,临时变量拿到的是"strength"这类字符串,字符串类型本身没有append()方法,既会触发运行报错,也不可能修改你提前定义的六个独立空列表。

推荐实现方式

不要零散定义六个独立的列表变量,直接用字典将属性名和对应的存储列表绑定,遍历逻辑清晰,也能直观练习列表append()方法的使用:

import random
# 字典结构同时存储属性名和对应的数值列表
stat_records = {
    "strength": [],
    "dexterity": [],
    "constitution": [],
    "intelligence": [],
    "wisdom": [],
    "charisma": []
}

random.seed(198421)

for stat in stat_records:
    # 生成4个六面骰点数
    d1 = random.randint(1,6)
    d2 = random.randint(1,6)
    d3 = random.randint(1,6)
    d4 = random.randint(1,6)
    point_sum = d1 + d2 + d3 + d4
    # 向对应属性的列表追加计算结果
    stat_records[stat].append(point_sum)

# 输出结果
print(f"Strength: {stat_records['strength']}")
print(f"Dexterity: {stat_records['dexterity']}")
print(f"Constitution: {stat_records['constitution']}")
print(f"Intelligence: {stat_records['intelligence']}")
print(f"Wisdom: {stat_records['wisdom']}")
print(f"Charisma: {stat_records['charisma']}")
保留原有独立变量的实现方式

如果需要保留你预先定义的六个单独列表,只需要把这些列表对象按属性顺序放到一个可遍历的容器中即可,不要遍历属性名字符串:

import random
stats = ["strength","dexterity","constitution","intelligence","wisdom","charisma"]
strength = []
dexterity = []
constitution = []
intelligence = []
wisdom = []
charisma = []

# 按属性顺序组装列表容器,遍历的时候直接拿到目标列表对象
stat_list = [strength, dexterity, constitution, intelligence, wisdom, charisma]

random.seed(198421)
for target_list in stat_list:
    d1 = random.randint(1,6)
    d2 = random.randint(1,6)
    d3 = random.randint(1,6)
    d4 = random.randint(1,6)
    target_list.append(d1+d2+d3+d4)

# 原有打印逻辑无需修改
print("Strength: "+ str(strength))
print("Dexterity: " + str(dexterity))
print("Constitution: "+ str(constitution))
print("Intelligence: "+ str(intelligence))
print("Wisdom: " + str(wisdom))
print("Charisma: " + str(charisma))
列表方法使用提示
  • append(x):原地修改列表,在列表末尾追加单个元素x,方法返回值为None
  • remove(x):原地修改列表,删除列表中**第一个值等于x**的元素,如果列表中不存在x会直接抛出ValueError,调用前建议先通过in判断元素是否存在

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 07:57:19