📜  从每个数字中减去 K 的Python程序

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

从每个数字中减去 K 的Python程序

给定一个列表,任务是编写一个Python程序,从每个数字中减去 K,如果元素低于 0,则保留 0。

例子:

方法一:使用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))


输出:

方法 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))

输出: