简体   繁体   中英

Adding string values together that are elements in a list

How would I go about doing the following? 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']

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. the second part is the card suit ie. C for Clubs or H for hearts. 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']

Is this helping. it will help regardless of the number position in them element.

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 =

There are a few ways to do this and I suggest you review the Python documentation on slicing and indexing strings.

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.

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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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