Python 程式查詢字串列表中字元 ASCII 值的總和
在本文中,我們將學習一個 Python 程式,用於查詢字串列表中字元的 ASCII 值之和。
使用的方法
以下是完成此任務的各種方法 -
使用 for 迴圈、+ 運算子、ord() 函式
使用列表推導式、sum()、ord() 函式
示例
假設我們已經獲取了一個包含字串元素的輸入列表。我們將找到@@
輸入
Input List: ['hello', 'tutorialspoint', 'python', 'platform']
輸出
[52, 209, 98, 101]
這裡,每個列表元素(例如hello)的所有字元的 ASCII 值之和為8+5+12+12+15 = 52,其中 ASCII (h) = 104,起始 ASCII 值即 ASCII (a) = 96,所以 104-96 得出 8。
方法 1:使用 for 迴圈、+ 運算子、ord() 函式
演算法(步驟)
以下是執行所需任務的演算法/步驟 -。
建立一個變數來儲存輸入列表並列印給定的列表。
建立一個空列表來儲存列表中所有字串元素的 ASCII 值總和。
使用 for 迴圈遍歷輸入列表的每個元素。
取一個變數來儲存 ASCII 值之和並將其初始化為 0(asciiValsSum)。
使用另一個巢狀的 for 迴圈遍歷當前列表元素的每個字元。
使用ord() 函式獲取字元的 ASCII 值(將給定字元的 Unicode 程式碼作為數字返回),並將其新增到上述asciiValsSum 變數中。
使用append() 函式(將元素新增到列表的末尾)將 ASCII 值之和附加到結果列表中。
列印輸入列表中字元 ASCII 值之和的列表。
示例
以下程式使用 for 迴圈、sum() 和 ord() 函式返回字串列表中字元 ASCII 值之和 -
# input list inputList = ["hello", "tutorialspoint", "python", "platform"] # printing input list print("Input List:", inputList) # storing the total sum of ASCII values of all string elements of the list resultList = [] # traversing through each element of an input list for i in inputList: # initializing ASCII values sum as 0 asciiValsSum = 0 # traversing through each character of the current list element for char in i: # getting the ASCII value of the character using the ord() function and # adding it to the above asciiValsSum variable asciiValsSum += (ord(char) - 96) # appending ascii values sum to the resultant list resultList.append(asciiValsSum) # printing list of the sum of characters ASCII values in an input list print("List of the sum of characters ASCII values in an input list:", resultList)
輸出
執行上述程式將生成以下輸出 -
Input List: ['hello', 'tutorialspoint', 'python', 'platform'] List of the sum of characters ASCII values in an input list: [52, 209, 98, 101]
方法 2:使用列表推導式、sum()、ord() 函式
列表推導式
當您希望根據現有列表的值構建新列表時,列表推導式提供了更短/簡潔的語法。
sum() 函式 - 返回可迭代物件中所有專案的總和。
演算法(步驟)
以下是執行所需任務的演算法/步驟 -
使用列表推導式遍歷字串列表中的每個字串。
使用另一個巢狀的列表推導式遍歷字串的字元。
從每個字元的 ASCII 值中減去基本 ASCII 值 (96)。
使用 sum() 函式獲取這些字元 ASCII 值的總和。
列印輸入列表中字元 ASCII 值之和的列表。
示例
以下程式使用列表推導式、sum() 和 ord() 函式返回字串列表中字元 ASCII 值之和 -
# input list inputList = ["hello", "tutorialspoint", "python", "platform"] # printing input list print("Input List:", inputList) # Traversing in the given list of strings (input list) # Using nested list comprehension to traverse through the characters of the string # Calculating resulting ASCII values and getting the sum using sum() function resultList = [sum([ord(element) - 96 for element in i]) for i in inputList] # printing list of the sum of characters ASCII values in an input list print("List of the sum of characters ASCII values in an input list:\n", resultList)
輸出
執行上述程式將生成以下輸出 -
Input List: ['hello', 'tutorialspoint', 'python', 'platform'] List of the sum of characters ASCII values in an input list: [52, 209, 98, 101]
結論
在本文中,我們學習瞭如何使用兩種不同的方法來計算字串列表中字元 ASCII 值的總和。此外,我們學習瞭如何使用巢狀列表推導式而不是巢狀迴圈。此外,我們學習瞭如何使用 ord() 方法獲取字元的 ASCII 值。