0

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']

  • Does this answer your question? [How to concatenate items in a list to a single string?](https://stackoverflow.com/questions/12453580/how-to-concatenate-items-in-a-list-to-a-single-string) – Yoshikage Kira Jun 01 '21 at 04:59

4 Answers4

1

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)
-1

You should avoid using function names as variable names i.e. 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)
  • 1
    This assumes that each string value would always have only a single leading number character (perhaps true, but the OP did not mention this). – Tim Biegeleisen Jun 01 '21 at 05:04
-1

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
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
-1

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)