Python编程实现将列表s=[2, 4, 2, 3, 1, 2, 3, 4 ,5, 8, 4, 3]中的偶数变为它的平方,奇数保持不变。
s = [2, 4, 3, 1, 2, 3, 4, 5, 8, 4, 3]
print("变换前:", s)
for i in range(0, len(s)):
if s[i] % 2 == 0: #s[i]为对应s列表中下标为i的元素
s[i] = s[i]*s[i]
print("变换后:", s)
# 运行效果如下:
变换前: [2, 4, 3, 1, 2, 3, 4, 5, 8, 4, 3]
变换后: [4, 16, 3, 1, 4, 3, 16, 5, 64, 16, 3]
运行效果如下:
变换前: [2, 4, 3, 1, 2, 3, 4, 5, 8, 4, 3]
变换后: [4, 16, 3, 1, 4, 3, 16, 5, 64, 16, 3]