How to find the sum of cartesian elements in python 3? - python

I want to find sum of Cartesian elements.
My Cartesian list is :[ ('1','2'),('3','4') ]
I want to find the sum of 1+2 and 3+4 and store it into another list.

x = [ ('1','2'),('3','4') ] # Your list
y = [int(a)+int(b) for a,b in x] # y is the sum you want
The second line is a list comprehension that iterates over every element in your list.
Each element is a tuple. By assigning a,b to that tuple, the first element of the tuple goes in a and the second in b.
We convert a and b from strings to integers and we add these integers.
(You mention "Cartesian list", but in Python terminology, each element is just a tuple. Perhaps you mean that a Cartesian product of two lists would typically result in a list of tuples.)
EDIT: Another approach, based on #U10-Forward's answer below, is y = map(sum, map(lambda e: map(int, e), x))

You could also use map as well:
l = [ ('1','2'),('3','4') ]
print(list(map(lambda x: int(x[0]) + int(x[1]), l)))

Using a namedtuple will allow you to add clarity to your code
Since you already have a list of string tuples
my_list = [('1', '2'), ('3', '4')]
You can first convert them to int
my_list = [(int(x), int(y)) for (x, y) in my_list]
Then introduce a namedtuple
my_list = [Point(x, y) for (x, y) in my_list]
Now your list looks something like this:
[Point(x=1, y=2), Point(x=3, y=4)]
And doing summation of x and y for each Point should be as easy as
sum_of_x_y = [point.x + point.y for point in my_list]
Output:
[3, 4] # sum_of_x_y

Related

Find the smallest value in a list with tuples inside a sublist

I need to find the smallest value in a list. The list has sublists which contains tuples. I need to find the smallest value in all of those tuples, but it can only include the first 3 values. I managed to achieve with the following code, but I want it to look cleaner.
lst = [[(1, 2, 3, 50)], [(0.2, 0.4, 2, 0.1)], [(0.6, 0.8, 1.2, 0.05)]]
def FitScoreSearch3(fitscores):
fitscores2 = []
for x in fitscores:
for y in x:
for z in y[:3]:
fitscores2.append(z)
return min(fitscores2)
The output is 0.2 as it should be. The output can't be 0.05.
Do your sublists always contain just a single tuple? If so,
def FitScoreSearch3(fitscores):
return min(min(x[0][:3]) for x in fitscores)
If the sublists are allowed to contain several tuples:
def FitScoreSearch3(fitscores):
return min(min(y[:3]) for x in fitscores for y in x)
In both cases, this swaps your loops for generator expressions. Also, instead of collecting all the numbers into one big list and then do the min(), the above compute the min() first on the tuple (or rather the first 3 elements of the tuple), after which the global minimum value is computed as the min() of all these "sub-min values". As this does not create an additional data structure, it's faster.
min([value for sublist in lst for value in sublist[0][:3]])
In this code lst2 contains all the values of the first 3 elements of each tuple.
lst2 = [ x for sublist in lst for tpl in sublist for x in tpl[:3] ]
print(min(lst2)) # 0.2
You could do something like -
def fitScoreSearch3(fitScores):
lst = list(map(lambda x: list(x[0][:3]), fitScores))
minimum = min(list(map(min, lst)))
return minimum

How to convert tuple to list with float and string values

I have a list of tuples like this:
tuple_list = [(['MATH120'], 3.665, 0.4737615433949868), (['GER'], 3.4566666666666666, 0.3967146329542181), (['FREE'], 3.415636363636364, 0.450256863026264), ([''], 0.041607963246554365, 0.38832820111766464)]
and what I want to do is convert this to:
result = [['MATH120', 3.665, 0.4737615433949868],['GER', 3.4566666666666666, 0.3967146329542181],['FREE', 3.415636363636364, 0.450256863026264]]
meaning that I want to convert it into a list of 3 pairs and delete the whole tuple if the list it has inside has only elements that are empty and delete also the empty strings that might exist in the tuple for example if it was like this:
tuple_list = [(['MATH120',''], 3.665, 0.4737615433949868), (['GER','',''], 3.4566666666666666, 0.3967146329542181), (['FREE'], 3.415636363636364, 0.450256863026264), ([''], 0.041607963246554365, 0.38832820111766464)]
I want it to turn to the same as previous:
result = [['MATH120', 3.665, 0.4737615433949868],['GER', 3.4566666666666666, 0.3967146329542181],['FREE', 3.415636363636364, 0.450256863026264]]
I tried doing this in order to put them just in list:
result= [list(map(list, l)) for l in tuple_list]
but I kept on getting error because of the float values:
TypeError: 'float' object is not iterable
If your data is always regular like that, and you only want the first element in the inner lists, then simply:
>>> [[x, y, z] for [x, *_], y, z in data]
[['MATH120', 3.665, 0.4737615433949868], ['GER', 3.4566666666666666, 0.3967146329542181], ['FREE', 3.415636363636364, 0.450256863026264], ['', 0.041607963246554365, 0.38832820111766464]]
FINAL EDIT:
Since you've clarified that they are empty strings, we can do something a little nicer:
>>> [ [*filter(None, lst), a, b] for lst, a, b in data if any(lst) ]
[['MATH120', 3.665, 0.4737615433949868], ['GER', 3.4566666666666666, 0.3967146329542181], ['FREE', 3.415636363636364, 0.450256863026264]]
>>>
Which I actually think is quite nicely declarative
result= [ [e for e in l if e] + list(t) for l, *t in tuple_list if any(l) ]
[e in t[0] if e] removes empty strings from a sublist; then the remaining elements of the tuple are appended; but if there are no non-empty elements in a list (any(t[0]) is False) then this tuple is skipped.
The reason you get this error is because when you call map(list, l), l refers to an inner tuple (E.G. (['MATH120'], 3.665, 0.4737615433949868)), and those floats cannot be converted to a list directly. I recommend doing something like the following:
for listIndex in range(tuple_list):
tuple_list[listIndex] = list(tuple_list[listIndex]) # Converts inner tuples to list
for element in inner_tuple:
if isinstance(element, list): # checks if element inside tuple is list
#do logic on list that you need
If your first element is always a list in your tuple, just account for it in more hardcoded way. It will only work with data in same format as examples you presented, list(tuple(list(...), ...), ...)
result_list = []
for x in tuple_list:
temp_tuple = []
if (len(x[0]) == 1 and x[0][0] == '') or len(x[0]) == 0:
continue
for y in x[0]:
if y == '':
continue
temp_tuple.append(y)
for y in range(1, len(x)):
temp_tuple.append(x[y])
result_list.append(temp_tuple)
I tested and result on examples and output was like you asked.
This solution is not one-line solution like other answers. But I personally prefer to avoid one-line loops in python if I can. That makes it easier for me to read it.
You just had one level too much. Use this:
result = [list(x) for x in tuple_list]
or
result = list(map(list, tuple_list))

How to iterate a zip list and print each index of it after joining to lists of the same size?

Given the variables:
X = ['a', 'b', 'c']
Y = [1, 2, 3]
complete the following statement:
[print(pair) for pair in ...]
so as to print to the screen pairs of elements from X and Y which occupy the same position in the index.
I know I can make a join X and Y and make a list using list(zip(X,Y)) but the adding that in the statement gives an empty list.
I can't solve this problem using the form required any help?
thanks!
Not really clear what you're trying to achieve. If you need to print pairs, zip works, i.e.
for pair in zip(X, Y):
print(pair)
[print(pair) for pair in ...] is list comprehension, this is made to create lists, not to print data:
pairs_list = [pair for pair in zip(X, Y)] # don't do this
which is simply pairs_list = list(zip(X, Y)). Does this make sense to you?
Using list comprehensions to leverage a sideeffect (like printing something) is frowned upon. If you dont need a list, don't build one.
[print(pair) for pair in zip(X,Y)] # no need to list(zip(...))
will result in lots on None ... because the return value of print() is None.
Use a simple loop:
for p in zip(X,Y):
print(p)

Removing duplicates from a list of tuples in python

I have a list of tuples, and I want to remove duplicate tuples. Something like this.
x = [['aaron','jeng'],['sdf','wqd'],['aaron','jeng']]
I want the output something like this :
y = [['aaron','jeng'],['sdf','wqd']]
How can I do that in an easy way? I can write code to do that, but is there any inbuilt function for this?
Edit 1 : As everyone has suggested, I'm sorry to call them tuples. I meant a list of lists. Thank You.
Your x value does not contain a list of tuples, but a list of lists. If it did contain a list of tuples:
x = [('aaron','jeng'),('sdf','wqd'),('aaron','jeng')]
out = set([i for i in x])
print(list(out))
[('aaron', 'jeng'), ('sdf', 'wqd')]
That's a list of lists... But no matter, you can use a temporary set to make sure there are no repeats:
x = [['aaron','jeng'],['sdf','wqd'],['aaron','jeng']]
seen = set() # store here the visited tuples
y = [e for e in x if tuple(e) not in seen and not seen.add(tuple(e))]
# [['aaron', 'jeng'], ['sdf', 'wqd']]
If you convert your inner lists to tuples upfront it will have a considerably better performance.
If you don't need to preserve the order, then just convert the inner lists to tuples and turn your x to a set().
This would be easy with a list of tuples, you would simply need set(x). Since your list is a list of lists, and not a list of tuples, you can convert them first:
set(tuple(i) for i in x)
returns:
{('aaron', 'jeng'), ('sdf', 'wqd')}
Or, if you want to reconvert to a list of lists as you had it:
[list(t) for t in (set(tuple(i) for i in x))]
# [['aaron', 'jeng'], ['sdf', 'wqd']]
You can use enumerate and any:
x = [['aaron','jeng'],['sdf','wqd'],['aaron','jeng']]
new_x = [[a, b] for i, [a, b] in enumerate(x) if not any(c == b for _, c in x[:i])]
Output:
[['aaron', 'jeng'], ['sdf', 'wqd']]
You do not have tuples, you have lists inside lists.
x = [['aaron','jeng'],['sdf','wqd'],['aaron','jeng']]
uniques = list (set ( tuple(a) for a in x))
Is a generator expression fed into a set thats then fed to a list resulting in
[('aaron', 'jeng'), ('sdf', 'wqd')]
What about converting to a dict , Because dict can have unique keys :
x = [['aaron','jeng'],['sdf','wqd'],['aaron','jeng']]
print({tuple(i):i for i in x}.values())
output:
[['aaron', 'jeng'], ['sdf', 'wqd']]

How can I apply a function to elements inside my list?

How can I multiply everything in my list by a number or how can I just apply a random function to my elements?
I have no idea how to do this.
list comprehension:
y = [x*2 for x in l]
lambda function:
y = map(lambda for x: x * 5, in l)
looping each element of the list:
for x in l:
There are hundreds of ways to achieve this. To get each element of the list you can use the following:
for element in list:
print element
function(element)
print element * 4
My mistake, i meant through decimals, my question was not clear enough. I'm running a function F through all the elements in my list but it is only going through the whole numbers in the list but i want it to run through decimals as well.
x = f(y) for y in x:
and my list is x = [0,2] but i need it to run through the decimal values as well.

Categories

Resources