convert string elements in list as integers in python - string

I have a list named newlist
newlist=[['24,4,17,46,0,43'], ['11,43,17'], ['33,17,43,4'], ['74,21'],['21,43,43,74,68,21']]
I need to convert each list element as integers.i.e.
newlist=[[24,4,17,46,0,43], [11,43,17], [33,17,43,4], [74,21], [21,43,43,74,68,21]].
Can anyone help me please.

Python 3:
newlist=[['24,4,17,46,0,43'], ['11,43,17'], ['33,17,43,4'], ['74,21'],['21,43,43,74,68,21']]
mylist = list(map(lambda x : list(map(int, x[0].split(','))) , newlist))
print(mylist)
Python 2:
newlist=[['24,4,17,46,0,43'], ['11,43,17'], ['33,17,43,4'], ['74,21'],['21,43,43,74,68,21']]
mylist = map(lambda x : map(int, x[0].split(',')) , newlist)
print mylist

Related

List comprehension flat list?

I have the following toy function:
def foo(a):
return [a+5]
And I am running the following code:
my_lst = [foo(x) for x in range(10) if x%2 == 0]
Getting:
[[5], [7], [9], [11], [13]]
But need:
[5,7,9,11,13]
But I want to get a plain list, not a list of lists.
How can I do it without itertools.chain.from_iterable(my_lst) but with list comprehension?
What is the best practice? itertools or list comprehension in this case?
Please advice.
I have tried:
[j[0] for j in [foo(x) for x in range(10) if x%2 == 0]]
Should I do it like this or there is a better way?
With list comprehension, it's done using two for loops:
my_lst = [subx for x in range(10) if x%2 == 0 for subx in foo(x)]
Also if you have a list of lists of one elements, you can "transpose" after the fact the list using zip:
bad_lst = [foo(x) for x in range(10) if x%2 == 0]
[my_lst] = zip(*bad_lst)
Or you can "transpose" using a list comprehension combined with list unpacking as well if you truly want a list as output and not a tuple:
bad_lst = [foo(x) for x in range(10) if x%2 == 0]
my_lst = [x for [x] in bad_lst]
alternatively to Laernes answer, you can also use itertools as :
list(itertools.chain(*[foo(x) for x in range(10) if x%2 == 0]))
or
list(itertools.chain.from_iterable([foo(x) for x in range(10) if x%2 == 0]))
More options here:
Your function should return a number, not a list:
def foo(a):
return a+5

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.

Adding an x in front of and after words in a list

It's basic as far as Python goes, but I need to create a function List of words as an input parameter and outputs them as a single String formatted as a sentence with a period at the end and lower case 'x's around each word.
e.g.
Input: ["This", "is", "a", "sentence"]
Returns: "xThisx xisx xax xsentencex.
I think I need a for loop, but I keep getting errors in trying them.
Thanks in advance!
The closest I've come is through:
quote = ["This","is","a","sentence"]
def problem3(quote):
blue='x x '.join(quote)
return(blue)
which returns "Thisx x isx x ax x sentence"
quote = ["This","is","a","sentence"]
s = ""
for word in quote:
s = s + "x" + word + "x "
s = s[:-1]
print(s)
Out[17]: 'xThisx xisx xax xsentencex'
list_ = ["This", "is", "a", "sentence"]
string =''
for item in list_:
string += ' x' +item+'x'
string = string.strip()
print(string)
Map the initial list
>>> list_ = ["This", "is", "a", "sentence"]
>>> newlist = list(map(lambda word: f"x{word}x", list_))
>>> print(newlist)
['xThisx', 'xisx', 'xax', 'xsentencex']
And then reduce it to get the complete sentence
>>> import functools
>>> result = functools.reduce(lambda a,b : f"{a} {b}", newlist2)
>>> print(result)
xThisx xisx xax xsentencex

convert list of key/value strings into map python

Convert list of key/value strings into map. Assume that the list contains only strings and that each string has exactly one ':' .
Is the following code a good approach? Does anyone know of a more elegant solution to this?
>>> l = ['name:number']
>>> l = {x[:x.find(':')] : x[x.find(':')+1:] for x in l}
>>> print(l)
{'name': 'number'}
An even simpler approach:
>>> l = ['name:number']
>>> dict(x.split(':') for x in l)
{'name': 'number'}

How to concatenate 2 list strings using list comprehension

I have 2 lists as below:
list1 = ['A','B']
list2 = ['C','D']
The required output should be [['AC','BC'], ['AD','BD']] using List comprehension.
Using two for loops as a list comprehension
list1= ['A','B']
list2= ['C','D']
b=[[l+p for l in list1] for p in list2]
print(b)

Resources