📜  Python程序在字符串列表中查找字符ascii值的总和

📅  最后修改于: 2022-05-13 01:54:36.289000             🧑  作者: Mango

Python程序在字符串列表中查找字符ascii值的总和

给定字符串列表,任务是编写一个Python程序来计算每个字符的 ASCII 值的总和值。

例子:

方法 1:使用ord() +循环

在这里,我们迭代每个字符中的每个字符串并继续添加位置值以获得其总和。总和值将附加到列表中的结果。

Python3
# Python3 code to demonstrate working of 
# Characters Positions Summation in String List
# Using ord() + loop
  
# initializing list
test_list = ["geeksforgeeks",
             "teaches", "us", "discipline"]
  
# printing original list
print("The original list is : " + str(test_list))
  
res = []
for sub in test_list:
    ascii_sum = 0
      
    # getting ascii value sum 
    for ele in sub :
        ascii_sum += (ord(ele) - 96)
          
    res.append(ascii_sum)
  
# printing result 
print("Position Summation List : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Characters Positional Summation in String List
# Using list comprehension + sum() + ord()
  
# initializing list
test_list = ["geeksforgeeks", "teaches", 
             "us", "discipline"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# sum() gets summation, list comprehension
# used to perform task in one line 
res = [sum([ord(ele) - 96 for ele in sub]) for sub in test_list]
  
# printing result 
print("Positional Summation List : " + str(res))


输出:

方法 2:使用列表推导+ sum() + ord()

在这里,我们使用 sum() 求和,ord() 用于获取 ASCII 位置值,而列表推导式为该问题提供了一种线性解决方案。

蟒蛇3

# Python3 code to demonstrate working of 
# Characters Positional Summation in String List
# Using list comprehension + sum() + ord()
  
# initializing list
test_list = ["geeksforgeeks", "teaches", 
             "us", "discipline"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# sum() gets summation, list comprehension
# used to perform task in one line 
res = [sum([ord(ele) - 96 for ele in sub]) for sub in test_list]
  
# printing result 
print("Positional Summation List : " + str(res))

输出: