Python 代码报错:将字符串列表元素错误地转换为整数

在使用 Python 代码生成随机句子时,遇到了一个错误:代码在第十行将输入的种子列表中的元素错误地转换为整数,实际上它们是字符串。

以下是修改后的代码:

import random

lst_who = ['horse', 'lamb', 'deer']
lst_what = ['watch a movie', 'listen to a story', 'have dinner']
lst_where = ['on the grass', 'in the cinema', 'at home']

# 输入种子作为随机数生成器的种子
seed_input = input().strip()
# 将输入的种子转换为字符串列表
seed = seed_input[1:-1].split(', ')

# 使用输入的种子设置随机数生成器的种子
random.seed(seed)

# 通过随机生成三个整数在闭区间[0, 2]范围内,作为索引访问三个列表,并拼接成句子
sentence = lst_who[random.randint(0, 2)] + ' ' + lst_what[random.randint(0, 2)] + ' ' + lst_where[random.randint(0, 2)]

# 输出句子
print(sentence)

修改后的代码能够正确地将输入的种子解析为字符串列表,并将其作为随机数生成器的种子。这样,代码应该能够正确运行并输出您期望的结果。

Python 代码报错:将字符串列表元素错误地转换为整数

原文地址: https://www.cveoy.top/t/topic/cpk9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录