这个 Python 程序有什么问题
What's Wrong In This Python Program
num1=int(input("Enter Number of Elements For first list :"))
list1=[]
for i in range(num1):
ele=[input("Enter element of list 1 :")]
list1.append(ele)
new_list = [(i,pow(i,2)) for i in list1]
print(list1)
print(new_list)
Traceback (most recent call last):
File "C:/Users/naray/AppData/Local/Programs/Python/Python39/touple6.py", line 8, in <module>
new_list = [(i,pow(i,2)) for i in list1]
File "C:/Users/naray/AppData/Local/Programs/Python/Python39/touple6.py", line 8, in <listcomp>
new_list = [(i,pow(i,2)) for i in list1]
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
问题:
- 您不能在列表上使用
pow()
,pow
总是在号码上被调用
解决方案:
- 无需将列表附加到
list1
,只需将输入转换为 int
并附加数字 ele
.
此代码应该可以正常工作
num1 = int(input("Enter Number of Elements For first list :"))
list1 = []
for i in range(num1):
ele = int(input("Enter element of list 1 :"))
list1.append(ele)
new_list = [(i, pow(i, 2)) for i in list1]
print(list1)
print(new_list)
输出:
Enter Number of Elements For first list :2
Enter element of list 1 :10
Enter element of list 1 :20
[10, 20]
[(10, 100), (20, 400)]
num1=int(input("Enter Number of Elements For first list :"))
list1=[]
for i in range(num1):
ele=[input("Enter element of list 1 :")]
list1.append(ele)
new_list = [(i,pow(i,2)) for i in list1]
print(list1)
print(new_list)
Traceback (most recent call last):
File "C:/Users/naray/AppData/Local/Programs/Python/Python39/touple6.py", line 8, in <module>
new_list = [(i,pow(i,2)) for i in list1]
File "C:/Users/naray/AppData/Local/Programs/Python/Python39/touple6.py", line 8, in <listcomp>
new_list = [(i,pow(i,2)) for i in list1]
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
问题:
- 您不能在列表上使用
pow()
,pow
总是在号码上被调用
解决方案:
- 无需将列表附加到
list1
,只需将输入转换为int
并附加数字ele
.
此代码应该可以正常工作
num1 = int(input("Enter Number of Elements For first list :"))
list1 = []
for i in range(num1):
ele = int(input("Enter element of list 1 :"))
list1.append(ele)
new_list = [(i, pow(i, 2)) for i in list1]
print(list1)
print(new_list)
输出:
Enter Number of Elements For first list :2
Enter element of list 1 :10
Enter element of list 1 :20
[10, 20]
[(10, 100), (20, 400)]