Python-Listの要素の一括操作

614 ワード

# List              
arr = [1,2,3,4,5,6,7,8,9,10]
print("The initial array is :",arr)
#   map   
def squ(x):
    return x ** 2
l1 = list(map(squ,arr))
print("Test 1 :")
print(l1)
#   for   
l2 = [i ** 2 for i in arr]
print("Test 2:")
print(l2)
#   for    +      
l3 = [squ(i) for i in arr]
print("Test 3 :")
print(l3)

実行結果:
The initial array is : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Test 1 :
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Test 2:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Test 3 :
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]