Python - 第 K 位数字总和
给定一个数字列表,提取第 K 个数字的总和。
Input : test_list = [5467, 34232, 45456, 22222, 3455], K = 2
Output : 19
Explanation : 6 + 2 + 4 + 2 + 5 = 19.
Input : test_list = [5467, 34232, 45456, 22222, 3455], K = 0
Output : 17
Explanation : 5 + 3 + 4 + 2 + 3 = 17.
方法 #1:使用str() + 循环
在这种情况下,我们将元素转换为字符串,然后通过使用循环提取它来计算仅第 K 个数字的总和。
Python3
# Python3 code to demonstrate working of
# Kth digit Sum
# Using loop + sum()
# initializing list
test_list = [5467, 34232, 45456, 22222, 3455]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
res = 0
for ele in test_list:
# adding Kth digit
res += int(str(ele)[K])
# printing result
print("Kth digit sum : " + str(res))
Python3
# Python3 code to demonstrate working of
# Kth digit Sum
# Using sum() + list comprehension + str()
# initializing list
test_list = [5467, 34232, 45456, 22222, 3455]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
# sum() getting summation
res = sum([int(str(ele)[K]) for ele in test_list])
# printing result
print("Kth digit sum : " + str(res))
输出:
The original list is : [5467, 34232, 45456, 22222, 3455]
Kth digit sum : 19
方法#2:使用sum() +列表推导+ str()
在这里,我们使用 sum() 执行获取总和的任务,并且使用列表理解来获得解决问题的单线方法。
蟒蛇3
# Python3 code to demonstrate working of
# Kth digit Sum
# Using sum() + list comprehension + str()
# initializing list
test_list = [5467, 34232, 45456, 22222, 3455]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
# sum() getting summation
res = sum([int(str(ele)[K]) for ele in test_list])
# printing result
print("Kth digit sum : " + str(res))
输出:
The original list is : [5467, 34232, 45456, 22222, 3455]
Kth digit sum : 19