【问题标题】:Python String object does not support error [closed]Python字符串对象不支持错误[关闭]
【发布时间】:2021-07-24 14:42:29
【问题描述】:

我正在学习 python,而我正在做这个练习......

student_scores = input("Input a list of student scores here ")

for n in range(0, len(student_scores)):
    student_scores[n] = int(student_scores[n])
print(student_scores)

highest_score = max(student_scores)
print(highest_score)


**i got the below error:** 
 line 5, in <module>
    student_scores[n] = int(student_scores[n])
TypeError: 'str' object does not support item assignment

【问题讨论】:

  • 嗯,你希望发生什么而不是?您正在尝试分配 number 来代替 immutable 字符串中的 character
  • 用你自己的话来说:当代码student_scores[n] = int(student_scores[n])运行时,你认为应该发生什么?显示一个示例,说明您对 student_scores 之前和之后的期望。我什至无法猜测您希望整个代码做什么。请阅读How to Ask提出实际问题。告诉我们您要解决什么问题,并附上一个以? 结尾的问题。
  • 友好一点吧,伙计们!关于 python 的一些事情让学习者感到惊讶,比如字符串是不可变的(在许多语言中并非如此)。

标签: python python-3.x string object oop


【解决方案1】:

就像错误说您不能将字符串分配给项目一样。所以我认为你正在寻找的是函数split()。现在假设用户输入了 10 个用空格分隔的数字,split() 会将它们变成一个字符串列表。然后您可以遍历每个字符串并将它们转换为整数。

student_scores = input("Input a list of student scores here ")
student_scores=student_scores.split()
for n in range(0, len(student_scores)): 
    student_scores[n] = int(student_scores[n]) 
    print(student_scores)

highest_score = max(student_scores) 
print(highest_score)

下面是使用列表理解的单行代码。它看起来很酷,所以我把它放在这里。

x = max([int(num) for num in input("Input a list of student scores here ").split()])

【讨论】:

  • 请注意,不需要列表推导——生成器表达式或map 也可以正常工作,而无需在内存中创建整个临时列表。例如,max(map(int, input("Input a list of student scores here ").split()))
  • 实际上,当我运行上面的代码时,为什么要打印 5 次列表值。这是输出: 在此处输入学生分数列表 [45, '54', '54', '78', '95', '42'] [45, 54, '54', '78', '95 ', '42'] [45, 54, 54, '78', '95', '42'] [45, 54, 54, 78, '95', '42'] [45, 54, 54, 78 , 95, '42'] [45, 54, 54, 78, 95, 42] 95
  • 你是怎么输入数字的?
猜你喜欢
  • 1970-01-01
  • 2019-01-13
  • 2015-09-13
  • 1970-01-01
  • 1970-01-01
  • 2010-09-17
  • 2011-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多