给出一个正整数列表,您必须找到可被3整除的数字并将其替换为它们的平方。
例如,考虑以下列表:
输入:
[1,2,3,4,5,6]
以上列表的输出为:
[1,2,9,4,5,36]
这是我一直在努力的:
import ast,sys
input_str = sys.stdin.read()
input_list = ast.literal_eval(input_str)
myInt = 3
new_list = [x / myInt for x in input_list]
def square(input_list)
if x/3:
for x in input_list
return x**2
print (square(input_list))
答案 0 :(得分:1)
input = [1,2,3,4,5,6]
new_list = [number**2 if number % 3 == 0 else number for number in input]
输出
[1, 2, 9, 4, 5, 36]
功能:
def fun_sqrt(input_list, number, sqrt):
new_list = [number**sqrt if number % number == 0
else number
for number in input_list
]
return new_list
您可以运行:
fun_sqrt(input_list, number=3, sqrt=2)
答案 1 :(得分:1)
list = [1,2,3,4,5,6]
for x in range(len(list)):
if list[x] % 3 == 0: list[x] = list[x]**2
print(list)
答案 2 :(得分:0)
inputList = [1,2,3,4,5,6]
newList = []
for item in inputList:
if item % 3 == 0:
newList.append(item*item)
else:
newList.append(item)
print(newList)