Adding string values together that are elements in a list - python

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)

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

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)

Related

Pick position of a list based on the position of another list in Python

Im a Python beginner and also new to Stackoverflow cant seem to find a solution to this problem and I have been looking around in weeks. It's an assignment and we cant use inbuild Python functions.
I want to find the position of an item in list A and choose the same position from list B. The item in list A should not be equal to zero. Once done, I have to add the corresponding value in B.
Eg:
A = [0,0,1,1]
B = [25,9,8,3]
A should result in position 2,3
B therefore equals to 8,3
8+3 = 11
Below is what I have tried so far
binary = [0,1,1,0,0,0]
decimal = [32,16,8,4,2,1]
output_decimal = []
for position in range(0, len(binary)):
if binary[position] !=0:
print(position)
I think this is what you wanted.
index = 0
sums = 0
binary = [0,1,1,0,0,0]
decimal = [32,16,8,4,2,1]
for value in binary:
if value == 1:
sums += decimal[index]
index += 1
print(sums)
If you don't need the positions you could just use the following
result = sum([y for x, y in zip(binary, decimal) if x])
In the list comprehension every pair of binary, decimal positions will be iterated and you only keep the decimal ones if the binary is not zero. Then you sum up all kept items.
import numpy as np
binary = np.array([0,1,1,0,0,0])
decimal = np.array([32,16,8,4,2,1])
values = np.where(binary == 1)
output_decimal = decimal[values[0]]
print(output_decimal)
This answer Done By using Numpy Package..
I think you got it. From your code, simply register the positions in the separate list that you created and then sum it up
binary = [0,1,1,0,0,0]
decimal = [32,16,8,4,2,1]
output_decimal = []
for position in range(0, len(binary)):
if binary[position] !=0:
output_decimal.append(decimal[position])
# to add everything
print(sum(output_decimal))
Output gives you: 16+8 = 24
so To find the position of an item in a list and select the same position from another list you can very much use a loop to iterate over the item in the first list. Inside the loop, you then check if the item is not equal to zero, and if it isn't, then you can add the appropriate value in the second list to the output list.
binary = [0,1,1,0,0,0]
decimal = [32,16,8,4,2,1]
output_decimal = []
# Iterate over the items in binary
for i, b in enumerate(binary):
# Check if the item is not equal to zero
if b != 0:
# If it is not, add the corresponding value in decimal to the output list
output_decimal.append(decimal[i])
# Print the output list
print(output_decimal)
so To count the sum of the values in the output list, you can simply use the built-in sum() function, like this:
total = sum(output_decimal)
if you don't want to use sum then you can use the code below:
total = 0
for value in output_decimal:
total += value
I think using enumerate may be good idea in this case:
result = sum([B[i] for i, val in enumerate(A) if val != 0])
print(result)

Multiply or duplicate number in a list. Python

How can I duplicate myData. For example
myLen = [1,2,3,4,5,6]
duplicate the number by the length of the 'myLen' and also convert the string to number
myData = ['2']
output:
[2,2,2,2,2,2]
try:
list(map(int,myData*len(myLen)))
What you could do is selecting the index of the element you need in myLen and then apply it to my data:
i = 0
n = myLen[i]
myData = ['2']**n
Of course you could decide what position you need by changing the value of i but make sure it's not greater than the length of myLen otherwise you'll get an error.
Basically the syntax [x]**n creates a list of length n with element x in it.

Python - Circular Shift Lists (but not the whole index)

so basically i want to make list shift left but only 1 digit from every index.
for example:
if i have this list [123,45678,90] i want to get this [234,56789,1]
another example just to make sure from this [12,34,56] i want to get this [23,45,61]
what ive done so far is
def main():
lst_lenght = int(input("Enter the lenght of the list:")) #amount of indexes
lst_elements = create_list(lst_lenght)
print(lst_elements)
def create_list(y):
lst = []
for i in range(y):
x = int(input('Enter the list elements:'))
lst.append(x)
return lst
then ive tried to do function that i will get the first digit of number(in every index)
after this i was just thinking removing the digit and placing it in the end of the index before it exept the first index which will go to the last one.
unfortunately i wasnt able to do it ive got stuck on this part, would love ur help, Thank you very much!!
You could do this with a list comprehension. Each element in the new list is defined by taking item[1:] (everything after the first digit in that item) plus next_item[0] (the first digit of the next item).
To do this, it's easier if you operate on it as a list of strings, and then convert back to integers to return.
def shifted_list(lst):
str_lst = [str(x) for x in lst]
str_lst_shifted_by_one = str_lst[1:] + [str_lst[0]]
shifted_str_lst = [item[1:] + next_item[0] for item, next_item in zip(str_lst, str_lst_shifted_by_one)]
return [int(x) for x in shifted_str_lst]
print(shifted_list([123,45678,90])) # [234, 56789, 1]

Finding the lowest number that does not occur at the end of a string, in a tuple in a list

I have a list of tuples, each has a single string as element 0, in these strings I want to get out the final number, and then find the lowest (positive) number that is not in this list.
How do you do this?
E.g. for the list tups:
tups=[('.p1.r1.c2',),('.p1.r1.c4',),('.p1.r1.c16',)]
the final numbers are 2, 4 and 16, so the lowest unused number is 1.
my attempt was this:
tups2= [tup[0] for tup in tups] # convert tuples in lists to the strings with information we are interested in
tups3 = [tup .rfind("c") for tup in tups2] # find the bit we care about
I wasn't sure how to finish it, or if it was fast/smart way to proceed
Where are you blocked? You can achieve that in basically two steps:
Step 1: Create the list of numbers
One way of doing this (inspired from there):
numbers = [int(s[0][len(s[0].rstrip('0123456789')):]) for s in tups]
In your example, numbers is [2, 4, 16].
Step 2: Find the lowest positive number that is not in this list
x = 1
while x in numbers:
x += 1
You didn't really specify your problem but I'm guessing that getting the lowest unused number is the issue.
the solutions above is great but it just gets the lowest number in the list and not the lowest unused one.
I tried to make a list of all the unused numbers then getting the minimum value of it.
I hope that would help
tups=[('15.p1.r1.c2',),('.poj1.r1.c4',),('.p2.r4.c160',)]
numbers = []
unused_numbers = []
for tup in tups:
words = tup[0].strip(".").split('.')
digits_list = [''.join(x for x in i if x.isdigit()) for i in words]
unused_numbers.extend(digits_list[:-1])
numbers.append(digits_list[-1])
print(numbers)
print(min(unused_numbers))
I used the same method Thibault D used to get a list of numbers:
tups=[('.p1.r1.c2',),('.p1.r1.c4',),('.p1.r1.c16',)]
num = [int(i[0][len(i[0].rstrip('0123456789')):]) for i in tups]
However, I used an easier method to get the minimum number:
min(num) - 1
This basically gets the lowest number in the list, and then subtracts 1 from it.

A function that calculates the average of a list and returns the elements that are greater than the mathematical average of the entire list

I'm trying to make a function that would calculate the average of a given list then returns all the elements within that list which are greater than the mathematical average of that list. Example:
if the given list is [1,2,3,4,5,6], the average would be 3.5. So the function should print out the numbers (4,5,6).
I've gotten as far as adding all the numbers up within the list but no matter what I do, I can't figure out how to get the average or get it to print out the numbers that are greater than the mathematical average.
This is what i have so far to add all the elements of any given list:
def accum2(seq):
total = 0
for x in seq:
total += x
return total
print (accum2([1,2,3,4,5,6]))
The expected result of print (accum2([1,2,3,4,5,6])) should be (4,5,6) but so far I just get an answer where it just adds up all the number in the given list.
Any help is greatly appreciated and thank you in advance.
The simplest way to get the average value of a list of numeric values is to use the methods:
average = sum(seq) / len(seq)
From there just use a conditional statement (you might have to sort the list first, if it is unsorted). From there you should be able to build a new list using the built in list methods.
heres some simple code which should work.
I have added comments.
originallist = [1,2,3,4,5,6] #This is your original list
outputlist = [] #This is the list which you can add correct values to
x = sum(originallist) / len(originallist) #This effectively finds you the average
for item in originallist: #Checks which items are greater than average
if item > x:
outputlist.append(item) #If greater, add to the final list
print(outputlist)
There are many correct ways to do this, one of which is shown below (Python 3).
lst = [1,2,3,4,5,6]
avg = sum(lst)/len(lst)
res = list(filter(lambda x: x > avg, lst))
print(res)
will produce
[4,5,6].
I prefer this approach because it's less verbose than loops and also can be more easily translated to a framework like Pandas or an eventual parallel implementation if such a need arises in the future (e.g., using Spark).
This is the extended version of your work:
def accum2(seq):
total = 0
for x in seq:
total += x
L=[]
for x in seq:
if x>total/len(seq):
L.append(x)
return L
print (accum2([1,2,3,4,5,6]))
But you could simply the previous one in this code:
def accum2(seq):
return [x for x in seq if x>(sum(y for y in seq)/len(seq))]
print (accum2([1,2,3,4,5,6]))

Categories

Resources