简体   繁体   English

在列表上执行sum()时如何替换python列表中的元素

[英]How to replace elements in python list when performing sum() on list

I have a python list containing integers and string data types. 我有一个包含整数和字符串数据类型的python列表。 All I need to do is to perform a replacement of the element when performing sum() function on the list. 我需要做的就是在列表上执行sum()函数时执行元素的替换。

For ex: The list is lis=[ 1, 4, 'Jan', 8] , I need to replace Jan with integer 1 when performing sum function on it. 例如:列表为lis=[ 1, 4, 'Jan', 8] ,在对它执行求和函数时,我需要用整数1替换Jan So the final output of sum function - sum(lis) becomes 1 + 4 + 1 + 8 which results to 14 . 因此,求和函数sum(lis)的最终输出为1 + 4 + 1 + 8 ,结果为14

There may be multiple such strings in the list and all those strings needs to be replaced when performing sum() on list. 列表中可能有多个这样的字符串,并且在列表上执行sum()时需要替换所有这些字符串。 Suppose Feb=2, Mar=3, Apr=4 , Feb replaced by 2 when sum() is called etc. 假设Feb=2, Mar=3, Apr=4Feb换成2sum()被调用等

I don't want the elements in the list to be replaced. 我不希望替换列表中的元素。 They should be replaced only when the sum is called. 仅在调用总和时才应替换它们。 Is there any inbuilt function or something to do that? 是否有任何内置函数或要执行的操作?

You want to map the elements of your list to values during summation. 您希望在求和期间将列表的元素映射到值。 You will need to create a function that does that (there could not be a built-in one for that, only you know the values). 您将需要创建一个用于执行此操作的函数(不可能有内置函数,只有您知道这些值)。 Something like 就像是

def f(value):
   if isinstance(value, int):
      return value
   return months[value]

where months is a dict like {'jan': 1, 'feb': 2...} months是像{'jan': 1, 'feb': 2...}这样的字典

Then 然后

sum([f(value) for value in my_list])

or 要么

sum(map(f, my_list))

You can use a dictionary that maps months to month number and then a list comprehension as follows 您可以使用将月份映射到月份数字的字典,然后按如下所示理解列表

months = { 'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5
          'Jun': 6, 'Jul': 7, 'Aug': 8, 'Sep':9, 'Oct':10
          'Nov':11, 'Dec':12 }
sum([months[x] if isinstance(x, str) else x for x in lis])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM