📜  Python|仅添加列表中存在的数值

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

Python|仅添加列表中存在的数值

给定一个包含字符和数字的列表,任务是只从列表中添加数字。下面给出了完成给定任务的一些方法。方法 #1:使用filter()lambda

# Python code to demonstrate
# how to add only numbers present
# in a list of characters and numbers
  
# initialising lists
ini_list = [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']
  
# printing initial list
print ("initial list", str(ini_list))
  
# code to add numbers from list
res = sum(filter(lambda i: isinstance(i, int), ini_list))
  
# printing result
print ("resultant sum", res)
输出:
initial list [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']
resultant sum 15


方法 #2:使用 try 和 except

# Python code to demonstrate
# how to add only numbers present
# in a list of characters and numbers
  
# initialising lists
ini_list = [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']
  
# printing initial list
print ("initial list", str(ini_list))
  
# code to add numbers from list
res = 0
for item in ini_list:
    try:
        res+= int(item)
    except ValueError:
        pass
  
# printing result
print ("resultant sum", res)
输出:
initial list [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']
resultant sum 15


方法 #3:使用 isinstance 和条件语句

# Python code to demonstrate
# how to add only numbers present
# in a list of characters and numbers
  
# initialising lists
ini_list = [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']
  
# printing initial list
print ("initial list", str(ini_list))
  
# code to add numbers from list
res = sum([x for x in ini_list if isinstance(x, int)])
  
# printing result
print ("resultant sum", res)
输出:
initial list [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']
resultant sum 15