Python TypeError:一元+;的操作数类型错误:';str';列入清单

Python TypeError:一元+;的操作数类型错误:';str';列入清单,python,Python,以下是我列出的清单: nums= [] for n in range(10): thenums= random.randint(10,90) print(thenums, end= " ") nums.append(thenums) 现在我需要帮助分别编写每个整数,但我在将列表中的每个数字写入文件中的一行时遇到了一个问题 with open("angles.txt", 'w') as h: for n in nums: h.write[str(n

以下是我列出的清单:

nums= []
for n in range(10):
    thenums= random.randint(10,90)
    print(thenums, end= " ")
    nums.append(thenums)
现在我需要帮助分别编写每个整数,但我在将列表中的每个数字写入文件中的一行时遇到了一个问题

with open("angles.txt", 'w') as h:
    for n in nums:
        h.write[str(n), + '\n'] 

你的语法太离谱了。线路

h.write[str(n), + '\n'] 
生成两个元素的元组,
str(n)
+'\n'
;后者抛出您的异常:

>>> + '\n'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'
但是,你也在尝试使用
h。像编写列表或字典一样编写

>>> h = open('/tmp/demo.txt', 'w')
>>> h.write['42\n']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'

你的语法太离谱了。线路

h.write[str(n), + '\n'] 
生成两个元素的元组,
str(n)
+'\n'
;后者抛出您的异常:

>>> + '\n'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'
但是,你也在尝试使用
h。像编写列表或字典一样编写

>>> h = open('/tmp/demo.txt', 'w')
>>> h.write['42\n']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'

h.write[str(n),+'\n']
h.write(str(n)+'\n')
?方括号(
[]
)用于列表索引,而不是函数调用,因此您的
h.write[
是无意义的。而且,
str(n),+'\n'
是一个语法错误,你在什么后面加了
'\n'
吗?我正在用'\n'在每个整数后面创建另一行。我相信…好的,明白了,谢谢你的帮助Kevin
h.write[str(n),+'\n']
h.write(str(n)+'\n')
?方括号(
[]
)用于列表索引,而不是函数调用,因此您的
h.write[
是胡说八道。此外,
str(n),+'\n'
是一个语法错误,你在什么后面附加了
'\n'
?我正在使用'\n'在每个整数后面创建另一行。我相信…好的,明白了,谢谢你的帮助。更改方手镯后逗号是问题。更改方手镯后逗号是问题。