简体   繁体   English

将作为列表中元素的字符串值相加

[英]Adding string values together that are elements in a list

How would I go about doing the following?我将如何 go 关于执行以下操作? I need to add the number in the various elements together and assign the total to a new variable.我需要将各个元素中的数字相加,并将总数分配给一个新变量。 I have been trying for days without much luck.我已经尝试了好几天没有太多运气。 I'm not sure if the numbers have to be split from the letters first?我不确定数字是否必须先从字母中分离出来?

list = ['2H','4B']列表 = ['2H','4B']

any help would be GREATLY appreciated.任何帮助将不胜感激。

edit:编辑:

Thanks for the replies eveyrone.谢谢大家的回复。 I dont know why I cant get this right it seems like it should be so simple.我不知道为什么我做不到这一点,它似乎应该如此简单。

I will give you guys some more infomration.我会给你们更多的信息。

the list below represents to playing cards, the first number or letter is the face value ie: 2 or 3 but can be a 'K' as well which stands for king and the value for that will be ten.下面的列表代表扑克牌,第一个数字或字母是面值,即:2 或 3,但也可以是代表国王的“K”,其值将是 10。 the second part is the card suit ie.第二部分是卡片套装,即。 C for Clubs or H for hearts. C 用于俱乐部或 H 用于红心。 I need to add the face value for these two cards together and get the hand total.我需要将这两张牌的面值相加并得到手牌总数。 a More accurate list might look like this.更准确的列表可能如下所示。

list1 = ['KH', '10C'] list1 = ['KH', '10C']

Is this helping.这有帮助吗。 it will help regardless of the number position in them element.无论它们元素中的数字 position 是多少,它都会有所帮助。

list1 = ['2H','4B']
list1=[word for x in list1 for word in x] #== Split the elements
print(list1)
new_var=0
for value in list1:
    try:
        value=int(value) #=== Convert to int
        new_var+=value #== Add value
    except ValueError:
        pass
print(new_var)

You should avoid using function names as variable names ie list =您应该避免使用 function 名称作为变量名称,即 list =

There are a few ways to do this and I suggest you review the Python documentation on slicing and indexing strings.有几种方法可以做到这一点,我建议您查看有关切片和索引字符串的 Python 文档。

l = ['2H','4B']

result = sum(int(x[0]) for x in l)
print(result)

result equals sum of first char of each element of the list.结果等于列表中每个元素的第一个字符的总和。 I have converted each indexed element zero to integer to allow addition.我已将每个索引元素零转换为 integer 以允许添加。

You can also do it the following way:您也可以通过以下方式执行此操作:

result = 0
for x in l:
    result += int(x[0])
print(result)

One approach, using a list comprehension along with re.findall to extract the leading digits from each list entry:一种方法是使用列表推导和re.findall从每个列表条目中提取前导数字:

list = ['2H','4B']
nums = [int(re.findall(r'^\d+', x)[0]) for x in list]  # [2, 4]
output = sum(nums)  # 6

You can extract numbers from each string then add them您可以从每个字符串中提取数字然后添加它们

You can use您可以使用

total = 0
list = ['2H','4B']
    
for element in list:
    res = [int(i) for i in element.split() if i.isdigit()]
    total += sum(res)

print(total)

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

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