我是 Python 3 的初学者,当我尝试这段代码时,它起作用了:
a = input('Enter three digits separated by space:')
b = a.split()
mylist = [int(i) for i in b]
print(mylist)
输出:
Enter three digits separated by space:2 3 4
[2, 3, 4]
但是当我尝试这样做时出现错误:
a = input('Enter three digits separated by space:')
b = a.split()
mylist = [int(i**2) for i in b]
print(mylist)
Error: TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
事实上这也有效:
list1 = [2,3,4]
mylist = [int(i**2) for i in list1]
print(mylist)
我做错了什么?
最佳答案
您可能想要在转换为 int
后进行求幂:
mylist = [int(i)**2 for i in list1]
您无法将字符串求幂(您知道字符串“blah”的平方是多少吗?),但可以将数字求幂。所以需要先将字符串转换为数字。
当然,a.split()
返回从原始字符串派生的较小字符串的列表,您必须自己将它们转换为数字,但您已经弄清楚了这一点。
关于python - 对输入字符串使用 split,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60304902/