最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python?List計算列表平方的9種常見方法

 更新時間:2024年03月29日 09:46:17   作者:0語1言  
平方操作是指將一個數(shù)值乘以自身,即計算數(shù)值的平方,這篇文章主要給大家介紹了關于Python?List計算列表平方的9種常見方法,文中通過代碼介紹的非常詳細,需要的朋友可以參考下

整理9種Python常見的計算列表平方的方法:

1. 使用for循環(huán)

此方法遍歷列表中的每個數(shù)字,使用 ** 運算符計算其平方,然后將結果添加到新的列表中。

numbers = [1, 2, 3, 4, 5]
squared_numbers = []
for num in numbers:
    squared_numbers.append(num ** 2)
print(squared_numbers)

2. 使用列表推導式

此方法使用列表推導式,這是一種更簡潔的方式,可以在現(xiàn)有列表的每個項目上執(zhí)行操作以創(chuàng)建新列表。

numbers = [1, 2, 3, 4, 5]
squared_numbers = [num ** 2 for num in numbers]
print(squared_numbers)

3. 使用map()函數(shù)和lambda函數(shù)

此方法使用map()函數(shù)和lambda函數(shù)來計算列表中每個數(shù)字的平方。

numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x ** 2, numbers))
print(squared_numbers)

4. 使用map()函數(shù)和定義的函數(shù)

與方法3類似,但是它使用單獨定義的函數(shù)square(x),而不是lambda函數(shù)。

numbers = [1, 2, 3, 4, 5]
def square(x):
    return x ** 2
squared_numbers = list(map(square, numbers))
print(squared_numbers)

5. 使用numpy庫

此方法使用numpy.square()函數(shù)來計算列表中每個數(shù)字的平方。

import numpy as np
numbers = [1, 2, 3, 4, 5]
squared_numbers = np.square(numbers)
print(squared_numbers)

6. 使用生成器表達式

此方法使用生成器表達式,這是列表推導式和生成器的高性能、內(nèi)存效率高的泛化。

numbers = [1, 2, 3, 4, 5]
squared_numbers = (num ** 2 for num in numbers)
squared_numbers = list(squared_numbers)
print(squared_numbers)

7. 使用math庫

此方法使用math.pow()函數(shù)來計算列表中每個數(shù)字的平方。

import math
numbers = [1, 2, 3, 4, 5]
squared_numbers = [math.pow(x, 2) for x in numbers]
print(squared_numbers)

8. 使用operator模塊

此方法使用operator.mul()函數(shù)來將列表中的每個數(shù)字與自身相乘。

import operator
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(operator.mul, numbers, numbers))
print(squared_numbers)

9. 使用帶有枚舉的循環(huán)

此方法使用enumerate()函數(shù)來獲取列表中每個數(shù)字的索引和值,然后使用 ** 運算符計算數(shù)字的平方。

numbers = [1, 2, 3, 4, 5]
squared_numbers = []
for i, num in enumerate(numbers):
    squared_numbers.append(numbers[i] ** 2)
print(squared_numbers)

附:python計算列表所有元素平方的實例代碼

方法一map()

#-*- coding:utf-8 -*-

def pow2(arg):
    return arg**2

def pow2List(listarg):
    mapObj = map(pow2, listarg)
    result = list(mapObj)
    return result

print(pow2List([1,-1,0,3,5]))

運行python文件,得到輸出:

[1, 1, 0, 9, 25]

方法二推導式

>>> list1 = [-1,0,5,6,15]
>>> [x**2 for x in list1]

總結 

到此這篇關于Python List計算列表平方的9種常見方法的文章就介紹到這了,更多相關Python List計算列表平方內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論

大悟县| 荃湾区| 陆河县| 太仆寺旗| 凉城县| 阿勒泰市| 彰化县| 台安县| 于都县| 东山县| 兴城市| 晴隆县| 澎湖县| 家居| 白城市| 葫芦岛市| 特克斯县| 宁晋县| 博湖县| 南陵县| 全椒县| 芷江| 大邑县| 包头市| 子长县| 长宁县| 新闻| 东乌| 新干县| 甘谷县| 闵行区| 开阳县| 南开区| 科技| 大安市| 玛曲县| 五华县| 从江县| 贺兰县| 颍上县| 芜湖市|