从每个数字中减去 K 的Python程序
给定一个列表,任务是编写一个Python程序,从每个数字中减去 K,如果元素低于 0,则保留 0。
例子:
Input : test_list = [2345, 8786, 2478, 8664, 3568, 28], K = 4
Output : [1, 4342, 34, 4220, 124, 4]
Explanation : In 2345, 4 subtracted from 2 is -2, hence ceiled to 0. Hence just 5-4 = 1, is retained. and thus output.
Input : test_list = [2345, 8786, 2478, 8664, 3568, 28], K = 3
Output : [12, 5453, 145, 5331, 235, 5]
Explanation : In 2345, 3 subtracted from 2 is -1, hence ceiled to 0. Hence just 5-3 = 2 and 4-3 = 1, are retained. and thus output.
方法一:使用str() + –运算符
在此,我们将整数转换为字符串并通过将每个数字转换为整数来执行减法,结果再次连接并将类型转换回整数。
Python3
# Python3 code to demonstrate working of
# Subtract K from each digit
# Using str() and - operator
# initializing list
test_list = [2345, 8786, 2478, 8664, 3568, 28]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
res = []
for ele in test_list:
str_ele = str(ele)
# getting maximum of 0 or negative value using max()
# conversion of each digit to int
new_ele = int(''.join([ str(max(0, int(el) - K)) for el in str_ele]))
res.append(new_ele)
# printing result
print("Elements after subtracting K from each digit : " + str(res))
Python3
# Python3 code to demonstrate working of
# Subtract K from each digit
# Using list comprehension
# initializing list
test_list = [2345, 8786, 2478, 8664, 3568, 28]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# list comprehension providing shorthand
res = [int(''.join([ str(max(0, int(el) - K)) for el in str(ele)]))
for ele in test_list]
# printing result
print("Elements after subtracting K from each digit : " + str(res))
输出:
The original list is : [2345, 8786, 2478, 8664, 3568, 28]
Elements after subtracting K from each digit : [1, 4342, 34, 4220, 124, 4]
方法 2:使用列表理解
与上述方法类似,仅使用列表理解来提供速记的任务。
蟒蛇3
# Python3 code to demonstrate working of
# Subtract K from each digit
# Using list comprehension
# initializing list
test_list = [2345, 8786, 2478, 8664, 3568, 28]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# list comprehension providing shorthand
res = [int(''.join([ str(max(0, int(el) - K)) for el in str(ele)]))
for ele in test_list]
# printing result
print("Elements after subtracting K from each digit : " + str(res))
输出:
The original list is : [2345, 8786, 2478, 8664, 3568, 28]
Elements after subtracting K from each digit : [1, 4342, 34, 4220, 124, 4]