📜  Python - 在给定索引处查找字符串长度的总和

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

Python - 在给定索引处查找字符串长度的总和

给定字符串列表,编写一个Python程序来计算列表的自定义索引的长度总和。

例子:

方法 #1:使用len() + 循环

在这里,我们迭代所有索引并检查它们是否出现在索引列表中,如果是,则在求和计数器中增加频率。

Python3
# Python3 code to demonstrate working of
# Length sum of custom indices Strings
# Using len() + loop
  
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# initializing idx list
idx_list = [0, 1, 4]
  
res = 0
for idx, ele in enumerate(test_list):
  
    # adding length if index in idx_list
    if idx in idx_list:
        res += len(ele)
  
# printing result
print("Computed Strings lengths sum : " + str(res))


Python3
# Python3 code to demonstrate working of
# Length sum of custom indices Strings
# Using sum() + len() + list comprehension
  
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# initializing idx list
idx_list = [0, 1, 4]
  
# performing summation using sum()
# len() used to get strings lengths
res = sum([len(ele) for idx, ele in enumerate(test_list) if idx in idx_list])
  
# printing result
print("Computed Strings lengths sum : " + str(res))


输出
The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
Computed Strings lengths sum : 10

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

在这里,我们使用 sum() 执行求和的任务,其余的所有功能都按照上述方法执行,就像单行一样。

蟒蛇3

# Python3 code to demonstrate working of
# Length sum of custom indices Strings
# Using sum() + len() + list comprehension
  
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# initializing idx list
idx_list = [0, 1, 4]
  
# performing summation using sum()
# len() used to get strings lengths
res = sum([len(ele) for idx, ele in enumerate(test_list) if idx in idx_list])
  
# printing result
print("Computed Strings lengths sum : " + str(res))
输出
The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
Computed Strings lengths sum : 10