How to convert a 3 column tuple without header to a two key single value dictionary in python? - python-3.x

Suppose I have two tuples, say:
l = (water, lily , 6)
m = (history , book, 5)
I want to convert it to a dictionary with 2 keys and a single value.
dict = {(water,lily): 6} {(history, book) : 5}
for the multiple line tuples in python.
How would I accomplish that?

You can use list comprehension.
l = [('water', 'lily' , 6), ('history' , 'book', 5)]
x = {(one, two): three for one, two, three in l}
print(x) # Prints {('water', 'lilly'): 6, ('history', 'book'): 5)}

Related

How to merge multiple tuples or lists in to dictionary using loops?

Here is my code to merge all tuple in to dictionary,
x = (1,2,3)
y = ('car',"truck","plane")
z=("merc","scania","boeing")
products={}
for i in x,y,z:
products[x[i]]= {y[i]:z[i]}
output:
error:
6 for i in x,y,z:
----> 7 products[x[i]]= {y[i]:z[i]}
8
9 print(products)
TypeError: tuple indices must be integers or slices, not a tuple
Now if i use indexing method inside loop for identifying positions like below code,
for i in x,y,z:
products[x[0]]= {y[0]:z[0]}
print(products)
out:
{1: {'car': 'merc'}}
here, I could only create what I need but only for a specified index how do create a complete dictionary using multiple lists/tuples??
is it also possible to use Zip & map functions?
Use zip to iterate over your separate iterables/tuples in parallel
list(zip(x, y, z)) # [(1, 'car', 'merc'), (2, 'truck', 'scania'), (3, 'plane', 'boeing')]
x = (1, 2, 3)
y = ("car", "truck", "plane")
z = ("merc", "scania", "boeing")
products = {i: {k: v} for i, k, v in zip(x, y, z)}
print(products) # {1: {'car': 'merc'}, 2: {'truck': 'scania'}, 3: {'plane': 'boeing'}}
You should use integer as indices.
x = (1,2,3)
y = ('car',"truck","plane")
z=("merc","scania","boeing")
products={}
for i in range(len(x)):
products[x[i]]= {y[i]:z[i]}
This should solve your problem
To add for above answer, I'm posting a solution using map,
x = (1,2,3)
y = ('car',"truck","plane")
z=("merc","scania","boeing")
products=dict(map(lambda x,y,z:(x,{y:z}),x,y,z))
print(products)

How to multiply 2 input lists in python

Please help me understand how to code the following task in Python using input
Programming challenge description:
Write a short Python program that takes two arrays a and b of length n
storing int values, and returns the dot product of a and b. That is, it returns
an array c of length n such that c[i] = a[i] · b[i], for i = 0,...,n−1.
Test Input:
List1's input ==> 1 2 3
List2's input ==> 2 3 4
Expected Output: 2 6 12
Note that the dot product is defined in mathematics to be the sum of the elements of the vector c you want to build.
That said, here is a possibiliy using zip:
c = [x * y for x, y in zip(a, b)]
And the mathematical dot product would be:
sum(x * y for x, y in zip(a, b))
If the lists are read from the keyboard, they will be read as string, you have to convert them before applying the code above.
For instance:
a = [int(s) for s in input().split(",")]
b = [int(s) for s in input().split(",")]
c = [x * y for x, y in zip(a, b)]
Using for loops and appending
list_c = []
for a, b in zip(list_a, list_b):
list_c.append(a*b)
And now the same, but in the more compact list comprehension syntax
list_c = [a*b for a, b in zip(list_a, list_b)]
From iPython
>>> list_a = [1, 2, 3]
>>> list_b = [2, 3, 4]
>>> list_c = [a*b for a, b in zip(list_a, list_b)]
>>> list_c
[2, 6, 12]
The zip function packs the lists together, element-by-element:
>>> list(zip(list_a, list_b))
[(1, 2), (2, 3), (3, 4)]
And we use tuple unpacking to access the elements of each tuple.
From fetching the input and using map & lambda functions to provide the result. If you may want to print the result with spaces between (not as list), use the last line
list1, list2 = [], []
list1 = list(map(int, input().rstrip().split()))
list2 = list(map(int, input().rstrip().split()))
result_list = list(map(lambda x,y : x*y, list1, list2))
print(*result_list)
I came out with two solutions. Both or them are the ones that are expected in a Python introductory course:
#OPTION 1: We use the concatenation operator between lists.
def dot_product_noappend(list_a, list_b):
list_c = []
for i in range(len(list_a)):
list_c = list_c + [list_a[i]*list_b[i]]
return list_c
print(dot_product_noappend([1,2,3],[4,5,6])) #FUNCTION CALL TO SEE RESULT ON SCREEN
#OPTION 2: we use the append method
def dot_product_append(list_a, list_b):
list_c = []
for i in range(len(list_a)):
list_c.append(list_a[i]*list_b[i])
return list_c
print(dot_product_append([1,2,3],[4,5,6])) #FUNCTION CALL TO SEE RESULT ON SCREEN
Just note that the first method requires that you cast the product of integers to be a list before you can concatenate it to list_c. You do that by using braces ([[list_a[i]*list_b[i]] instead of list_a[i]*list_b[i]). Also note that braces are not necessary in the last method, because the append method does not require to pass a list as parameter.
I have added the two function calls with the values you provided, for you to see that it returns the correct result. Choose whatever function you like the most.

Converting a list that contains integers and strings into a nested tuple, Python [duplicate]

This question already has answers here:
Pairs from single list [duplicate]
(10 answers)
Closed 4 years ago.
I wish to convert a string into a nested tuple for instance:
string = 'Jane A 3 B- 3 F 1#Bob C+ 2 D+ 3#Chris C 4 C 3 C- 2'
As you can see, the string is not normal with # signs and white-spaces in place of a comma. The # sign is what represents the number of names for which I have to compute some data that follows after each name. So I used string.split('#') to create 3 separate strings and from there, I used a for loop to get this on the first iteration:
['A', 3, 'B-', 3, 'F', 1]
The reason why 'Jane' is missing from the list is because I only need to take the values, whether it be a string or an integer, and make a nested tuple out of them. Thus, I wish to convert this list into a nested tuple that looks like:
[('A', 3), ('B-', 3), ('F', 1)]
I will greatly appreciate any help or suggestions.
I dont know if there is a better way, but here we go:
input = ['A', 3, 'B-', 3, 'F', 1]
l1 = input[::2] # get even
l2 = input[1::2] # get odd
tuples = list(zip(l1,l2)) # zip them together
# yes it could be wrote `tuples = list(zip(input[::2],input[1::2]))`
print (tuples)
Output
[('A', 3), ('B-', 3), ('F', 1)]
Try it online!
using regular expressions
>>> import re
>>> [[(mark, int(count))
for mark, count in map(str.split,
re.findall(r'[A-Z][+-]? \d+', student_data))]
for student_data in string.split('#')]
[[('A', 3), ('B-', 3), ('F', 1)],
[('C+', 2), ('D+', 3)],
[('C', 4), ('C', 3), ('C-', 2)]]
Step-by-step explanation
We're separating students (let's call them so) from each other since we need to store their "marks" (or what does these A/B/C/D with +/- mean?) in different containers:
string.split('#')
For each student we're searching "mark" data using regular expression
[A-Z][+-]? \d+
which can be read like
any capital Latin letter (which optionally may be followed by + or - sign) and a whitespace followed by digits
and pass it and student's substring to re.findall function. After that we will have something like:
>>> [re.findall(r'[A-Z][+-]? \d', student_data) for student_data in string.split('#')]
[['A 3', 'B- 3', 'F 1'], ['C+ 2', 'D+ 3'], ['C 4', 'C 3', 'C- 2']]
Finally we can use str.split method to separate letters with +/- from digits and iterate over this pairs converting second coordinates to int.
Further reading
map built-in docs.
re module docs.

Python: How to find the average on each array in the list?

Lets say I have a list with three arrays as following:
[(1,2,0),(2,9,6),(2,3,6)]
Is it possible I get the average by diving each "slot" of the arrays in the list.
For example:
(1+2+2)/3, (2+0+9)/3, (0+6+6)/3
and make it become new arraylist with only 3 integers.
You can use zip to associate all of the elements in each of the interior tuples by index
tups = [(1,2,0),(2,9,6),(2,3,6)]
print([sum(x)/len(x) for x in zip(*tups)])
# [1.6666666666666667, 4.666666666666667, 4.0]
You can also do something like sum(x)//len(x) or round(sum(x)/len(x)) inside the list comprehension to get an integer.
Here are couple of ways you can do it.
data = [(1,2,0),(2,9,6),(2,3,6)]
avg_array = []
for tu in data:
avg_array.append(sum(tu)/len(tu))
print(avg_array)
using list comprehension
data = [(1,2,0),(2,9,6),(2,3,6)]
comp = [ sum(i)/len(i) for i in data]
print(comp)
Can be achieved by doing something like this.
Create an empty array. Loop through your current array and use the sum and len functions to calculate averages. Then append the average to your new array.
array = [(1,2,0),(2,9,6),(2,3,6)]
arraynew = []
for i in range(0,len(array)):
arraynew.append(sum(array[i]) / len(array[i]))
print arraynew
As you were told in the comments with sum and len it's pretty easy.
But in python I would do something like this, assuming you want to maintain decimal precision:
list = [(1, 2, 0), (2, 9, 6), (2, 3, 6)]
res = map(lambda l: round(float(sum(l)) / len(l), 2), list)
Output:
[1.0, 5.67, 3.67]
But as you said you wanted 3 ints in your question, would be like this:
res = map(lambda l: sum(l) / len(l), list)
Output:
[1, 5, 3]
Edit:
To sum the same index of each tuple, the most elegant method is the solution provided by #PatrickHaugh.
On the other hand, if you are not fond of list comprehensions and some built in functions as zip is, here's a little longer and less elegant version using a for loop:
arr = []
for i in range(0, len(list)):
arr.append(sum(l[i] for l in list) / len(list))
print(arr)
Output:
[1, 4, 4]

how to print only duplicate numbers in a list?

I need to print only duplicate numbers in a list and need to multiply by count. the code is as follows , the output should be ,
{1:3, 2:2, 3:2} need to multiply each numbers by count and print as separate answers:
answer1 = 1*3, answer2 = 2*2 , answer3 = 3*2
Current attempt:
from collections import Counter
alist = [1,2,3,5,1,2,1,3,1,2]
a = dict(Counter(a_list))
print(a)
Counter already does the heavy lifting. So for the rest, what about generating a list of the values occuring more than once, formatting the output as you wish ? (sorting the keys seems necessary so indexes match the keys order):
from collections import Counter
a_list = [1,2,3,5,1,2,1,3,1,2]
a = ["{}*{}".format(k,v) for k,v in sorted(Counter(a_list).items()) if v > 1]
print(a)
result:
['1*4', '2*3', '3*2']
If you want the numerical result instead:
a = [k*v for k,v in sorted(Counter(a_list).items()) if v > 1]
result (probably more useful):
[4, 6, 6]
Assigning to separate variables (answer1,answer2,answer3 = a) is not a very good idea. Keep a indexed list

Resources