convert a 2d tuple into a list - list

i'm not very familiar with python, but i need to convert a 2d tuple into a nested list, i searched on stack i couldn't find an answer, Example:
Tuple = {(1,3),(3,5),(5,6)}
i need it to be a list:
List = [[1,3],[3,5],[5,6]]
why i need to convert a tuple, tuple wont allow me to use .replace on the content of the tuple
i tried to uselist() as stated on the internet but it didn't convert the tuple, thank you.

You can try like this,
>>> Tuple = {(1,3),(3,5),(5,6)}
>>> [list(item) for item in Tuple]
[[5, 6], [1, 3], [3, 5]]
Or, you can use map
>>> list(map(list, Tuple))
[[5, 6], [1, 3], [3, 5]]

You can simply use map function which performs better when you want to apply a built-in function on an iterable :
>>> Tuple = {(1,3),(3,5),(5,6)}
>>> list(map(list,Tuple))
[[5, 6], [1, 3], [3, 5]]

You can try this:
>>> Tuple = {(1,3),(3,5),(5,6)}
>>> [list(item) for item in Tuple]
[[5, 6], [1, 3], [3, 5]]
or You can use iterloops imap for better performance
>>>import itertools
>>> Tuple = {(1,3),(3,5),(5,6)}
>>> list(itertools.imap(list, Tuple))
[[5, 6], [1, 3], [3, 5]]

Related

How to update numpy column where column condition met?

If I have the following:
import numpy as np
a = np.array([[0, 1],
[1, 3],
[4, 4]])
And want to update the column value if a column condition is met. For example if the 2nd column value is greater than 2, then replace only that column value with 9.
a = [[0, 1],
[1, 9],
[4, 9]]
I would have thought this would work, but it updates all the values in that row.
a[a[:,1] > 2] = 9
But it replaces all the values in the row.
a =[[0, 1],
[9, 9],
[9, 9]]
I'm guessing I'm missing some understanding of how the boolean indexing is being created here.
You need:
import numpy as np
a = np.array([[0, 1],
[1, 3],
[4, 4]])
a[:,1]= np.where(a[:,1]>2, 9, a[:,1])
print(a)
Output:
array([[0, 1],
[1, 9],
[4, 9]])
why your code not working
try printing out print(a[a[:,1] > 2])
it will give output as:
[[1 3]
[4 4]]
It will check for 2nd index if it is greater than 2 it will return an entire row.

Zipp lists in python by iterating through a list of lists

I have two lists of lists as follows. To merge them, I usually do the following:
>>>from itertools import imap, ilist
>>>a = [1,2,3]
>>>b = [4,5,6]
>>> c = list(imap(list,izip(a,b)))
>>> c
[[1, 4]], [2, 5], [3, 6]]
However, now I have a list of list as follows:
[[1,2,3],
[4,5,6],
[7,8,9],
]
How do I iterate through each list and pass it to the izip function to obtain the following output:
[[1,4,7],[2,5,8],[3,6,9]]
Answer for edited Question:
>>> input_list=[[1,2,3],
[4,5,6],
[7,8,9],
]
Using map and zip:
>>> map(list,zip(*input_list))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Using imap and izip:
>>> list(imap(list,list(izip(*input_list))))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Answer for previous question:
By using list comprehension and two for loops:
input_list =[[[1],[2],[3]],
[[4],[5],[6]],
[[7],[8],[9]],
]
out_list = [[] for i in range(len(input_list))]
for each_row in input_list:
for i in range(len(each_row)):
out_list[i].extend(each_row[i])
print out_list
Output:
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
I think u need something like this:
input_list =[[1,2,3],
[4,5,6],
[7,8,9],
]
result = []
for i in range(len(input_list)):
temp = []
for list in input_list:
temp.append(list[i])
result.append(temp)
print result
result will be:
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Math operations between values in list and list of lists (python3)

I'm stuck on what seems to be an easy problem :
I've got 2 lists of lists, let says :
a = [[1], [2]]
b = [[1, 2, 3], [4, 5, 6]]
And I want this result :
result = [[2, 3, 4], [6, 7, 8]]
by adding (or, why not, substracting ) a[0] value to each value of b[0], then a[1] to b[1] etc...
I've tried using zip without result as expected:
result = [x for x in zip(a, b)]
Can someone help me to progress ?
you have a list of lists with 1 element, and you want to apply addition of that element on all elements of the other list. Since expected result is a list of lists, you have to create a double list comprehension, like this:
a = [[1], [2]]
b = [[1, 2, 3], [4, 5, 6]]
result = [[x+v for x in l] for [v],l in zip(a,b)]
print(result)
result:
[[2, 3, 4], [6, 7, 8]]
for [v],l is a neat way of unpacking the element inside the list so it avoids x+v[0] in the loop and it's more performant (and pythonic). Plus: if the list suddenly contains more than 1 element, you'll get an unpack error instead of an unexpected result (by ignoring further elements).
You can do this using numpy, which inherently supports array operations such as this:
>>> import numpy as np
>>> i = np.array([[1], [2]])
>>> j = np.array([[1, 2, 3], [4, 5, 6]])
>>> i+j
array([[2, 3, 4],
[6, 7, 8]])
If your lists are large, this may have a speed advantage over list comprehensions due to the fact that numpy uses fast low-level routines for this sort of stuff.
If not, and you don't already have numpy installed, then the overhead of installing another library is probably not worth it.

sum of items in a 2d list

Im trying ti implement a function evenrow() that takes a two dimensional list of integers and returns True if each row of the table sums up to an even number and False otherwise (i.e.., if some row sums up to an odd number)
usage
>>> evenrow([[1, 3], [2, 4], [0, 6]])
True
>>> evenrow([[1, 3], [3, 4], [0, 5]])
False
This is what I got so far:
def evenrow(lst):
for i in range(len(lst)-1):
if sum(lst[i])%2==0: # here is the problem, it only iterates over the first item in the lst [1, 3] - i cant figure this out - range problem?
return True
else:
False
How do I get the loop to iterate over every item [1, 3], [2, 4], [0, 6] in the list and not just the first?
well I have gotten this far now:
def evenrow(lst):
for i in range(len(lst)-1):
if sum(lst[i]) %2 >0:
return False
else:
return True
and i get the following answer when executing different lists:
>>> evenrow([[1, 3], [2, 4], [0, 6]])
True
>>> evenrow([[1, 3], [3, 4], [0, 5]])
False
>>> evenrow([[1, 3, 2], [3, 4, 7], [0, 6, 2]])
True
>>> evenrow([[1, 3, 2], [3, 4, 7], [0, 5, 2]])
True
(the last one is not correct though - should be False) I just dont get why this is not working...
You are returning too early. You should check for all the pairs, only returning True afterwards, or return False if a odd sum is encountered.
Spoiler alert:
def evenrow(lst):
for i in range(len(lst)-1):
if sum(lst[i]) % 2 != 0: # here is the problem, it only iterates over the first item in the lst [1, 3] - i cant figure this out - range problem?
return False
return True
This will achieve the goal.

Prolog - dividing a list in N parts

I'm trying to write a predicate that divides a list into N parts.
This is what I have so far.
partition(1, List, List).
partition(N, List, [X,Y|Rest]):-
chop(List, X, Y),
member(NextToChop, [X,Y]), %Choose one of the new parts to chop further.
NewN is N-1,
partition(NewN, NextToChop, Rest).
chop(List, _, _):-
length(List, Length),
Length < 2, %You can't chop something that doesn't have at least 2 elements
fail,!.
chop(List, Deel1, Deel2):-
append(Deel1, Deel2, List),
Deel1 \= [],
Deel2 \= [].
The idea is to keep chopping parts of the list into two other parts until I have N pieces.
I have mediocre results with this approach:
?- partition(2, [1,2,3,4], List).
List = [[1], [2, 3, 4], 1] ;
List = [[1], [2, 3, 4], 2, 3, 4] ;
List = [[1, 2], [3, 4], 1, 2] ;
List = [[1, 2], [3, 4], 3, 4] ;
List = [[1, 2, 3], [4], 1, 2, 3] ;
List = [[1, 2, 3], [4], 4] ;
false.
So I get what I want, but I get it two times and there are some other things attached.
When dividing into 3 parts things get worse:
?- partition(3, [1,2,3,4], List).
List = [[1], [2, 3, 4], [2], [3, 4], 2] ;
List = [[1], [2, 3, 4], [2], [3, 4], 3, 4] ;
List = [[1], [2, 3, 4], [2, 3], [4], 2, 3] ;
List = [[1], [2, 3, 4], [2, 3], [4], 4] ;
List = [[1, 2], [3, 4], [1], [2], 1] ;
List = [[1, 2], [3, 4], [1], [2], 2] ;
List = [[1, 2], [3, 4], [3], [4], 3] ;
List = [[1, 2], [3, 4], [3], [4], 4] ;
List = [[1, 2, 3], [4], [1], [2, 3], 1] ;
List = [[1, 2, 3], [4], [1], [2, 3], 2, 3] ;
List = [[1, 2, 3], [4], [1, 2], [3], 1, 2] ;
List = [[1, 2, 3], [4], [1, 2], [3], 3] ;
false.
Another idea is using prefix but I don't know how that would really work. To use that I should be able to let Prolog know that it needs to take a prefix that's not too short and not too long either, so I don't take a prefix that's too long so there's nothing left for a next recursion step.
Can anyone point me in the right direction?
Little clarification: the predicate should return all posibilities of dividing the list in N parts (not including empty lists).
When describing relations that involve lists, DCGs are often very useful. Consider:
list_n_parts(List, N, Parts) :-
length(Parts, N),
phrase(parts(Parts), List).
parts([]) --> [].
parts([Part|Parts]) --> part(Part), parts(Parts).
part([P|Ps]) --> [P], list(Ps).
list([]) --> [].
list([L|Ls]) --> [L], list(Ls).
Sample query:
?- list_n_parts([1,2,3,4], 2, Ps).
Ps = [[1], [2, 3, 4]] ;
Ps = [[1, 2], [3, 4]] ;
Ps = [[1, 2, 3], [4]] ;
false.
Here is the basic way I'd use to implement that (using append/2 and length/2) :
list_n_parts(List, Parts, Result) :-
length(Result, Parts),
append(Result, List).
Now, that doesn't totally complies to your expectations : it allows for [].
One idea to fix that is to use a maplist call to format the Resulting list beforehand :
list_n_parts(List, Parts, Result) :-
length(Result, Parts),
using copy_term/2, the maplist/2 call looks like :
maplist(copy_term([_|_]), Result),
using functor/3 (credits to #false), it would look like :
maplist(functor('.', 2), Result),
using lambda.pl you could write :
maplist(\[_|_]^true, Result),
since the '\' already performs a term copy (thanks #false).
The only thing left is the append/2 call:
append(Result, List).
Another idea would be to use forall/2 filtering (maybe simpler to get, but worse in complexity) :
list_n_parts(List, Parts, Result) :-
length(Result, Parts),
append(Result, List),
forall(member(X, Result), X \= []).
etc...