Converting matrix to an array in python [duplicate] - python

This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 10 years ago.
I have an array of array in python. What is the best way to convert it to an array in python?
for example:
m = [[1,2],[3,4]]
# convert to [1,2,3,4]
I am new in python, so I dont know any solution of it better than writing a loop. Please help.

Use itertools.chain or list comprehension:
from itertools import chain
list(chain(*m)) # shortest
# or:
list(chain.from_iterable(m)) # more efficient
For smaller lists comprehension is faster, for longer ones chain.from_iterable is more suitable.
[item for subl in m for item in subl]
For understanding the nested comprehension, you can split it across multiple lines and compare it to a regular for loop:
[item #result = []
for subl in m #for subl in m:
for item in subl] # for item in subl:
# result.append(item)

Related

How to make an array out of the nth element of items in a 2d array? [duplicate]

This question already has answers here:
How to extract the n-th elements from a list of tuples
(8 answers)
Get the nth element from the inner list of a list of lists in Python [duplicate]
(1 answer)
How to access the nth element of every list inside another list?
(3 answers)
Closed 1 year ago.
Not sure how to google this for the same reason I am not sure how to write the title.
basically if I have the array:
[[1,2,3],[4,5,6],[7,8,9]]
I want to pull say the 2nd(nth) item of each array and turn them into an array as such:
[2,5,8]
What is the quickest (preferably immediate) way to parse the array this way without using for-loops?
You can use list comprehension
x = [[1,2,3],[4,5,6],[7,8,9]]
y = [ele[1] for ele in x]
If you really don't want see loop or for, you can use map and lambda
x = [[1,2,3],[4,5,6],[7,8,9]]
y = list(map(lambda x:x[1],x))
If you don't consider a list comprehension a loop (even though it is certainly looping under the hood), you could accomplish this like:
list1 = [[1,2,3], [4,5,6], [7,8,9]]
list2 = [ e[1] for e in list1 ]

How to find sublist which present one list not another list in python? [duplicate]

This question already has answers here:
Removing duplicates from a list of lists
(16 answers)
Python: Remove duplicate lists in list of lists [duplicate]
(5 answers)
Closed 3 years ago.
I need to compare two lists which are basically list-of-list find out the sublists which are present in one list but not other. Also the arrangement of the sublists does not consider i.e. ['a','b'] = ['b,'a']. The two lists are
List_1 = [['T_1','T_2'],['T_2','T_3'],['T_1','T_3']]
List_2 = [['T_1','T_2'],['T_3','T_1']]
The output list should be
out_list = [['T_2','T_3']]
For two element sublists, this should suffice:
[x for x in List_1 if x not in List_2 and x[::-1] not in List_2]
Code:
List_1 = [['T_1','T_2'],['T_2','T_3'],['T_1','T_3']]
List_2 = [['T_1','T_2'],['T_3','T_1']]
print([x for x in List_1 if x not in List_2 and x[::-1] not in List_2])
Here's a little messy functional solution that uses sets and tuples in the process (sets are used because what you're trying to calculate is the symmetric difference, and tuples are used because unlike lists, they're hashable, and can be used as set elements):
List_1 = [['T_1','T_2'],['T_2','T_3'],['T_1','T_3']]
List_2 = [['T_1','T_2'],['T_3','T_1']]
f = lambda l : tuple(sorted(l))
out_list = list(map(list, set(map(f, List_1)).symmetric_difference(map(f, List_2))))
print(out_list)
Output:
[['T_2', 'T_3']]
I'd say frozensets are more appropiate for such task:
fs2 = set(map(frozenset,List_2))
out = set(map(frozenset,List_1)).symmetric_difference(fs2)
print(out)
# {frozenset({'T_2', 'T_3'})}
The advantage of using frozensets here is that they can be hashed, hence you can simply map both lists and take the set.symmetric_difference.
If you want a nested list from the output, you can simply do:
list(map(list, out))
Note that some sublists might appear in a different order, though given the task should not be a problem
You can convert lists to sets for equality comparison and use any() to add into list only items which doesn't exists in second list:
List_1 = [['T_1', 'T_2'], ['T_2', 'T_3'], ['T_1', 'T_3']]
List_2 = [['T_1', 'T_2'], ['T_3', 'T_1']]
out_list = [l1 for l1 in List_1 if not any(set(l1) == set(l2) for l2 in List_2)]
For better understanding resources consumption and efficiency of each answer I've done some tests. Hope it'll help to choose best.
Results on data from question:
Olvin Roght's answer - 12.963876624000001;
yatu's answer - 8.218290244000002;
rusu_ro1's answer - 8.857162503000001;
MrGeek's answer - 11.631234766000002;
Austin's answer - 3.452045860999995;
GZ0's answer - 7.037438627.
Results on bigger data:
Olvin Roght's answer - 83.452110953;
yatu's answer - 0.1939603360000035;
rusu_ro1's answer - 0.24479892000000802;
MrGeek's answer - 0.32636319700000627;
Austin's answer - 5.052051797000004;
GZ0's answer - 0.20400504799999908.
if you do not have duplicates in your lists you can use:
set(frozenset(e) for e in List_1).symmetric_difference({frozenset(e) for e in List_2})
output:
{frozenset({'T_2', 'T_3'}), frozenset({1, 2})}
if you need a list of lists as output you can use:
[list(o) for o in output]
ouptut:
[['T_2', 'T_3']]
Here is a one-liner variant of the frozenset solutions from #yatu and #rusu_ro1 for those who prefer a more concise syntax:
out = [*map(list,{*map(frozenset,List_1)}^{*map(frozenset,List_2)})]
If it is not required to convert the output into a nested list, just do
out = {*map(frozenset,List_1)}^{*map(frozenset,List_2)}
Meanwhile, one advantage of using the symmetric_difference function rather than the ^ operator is that the former can take any iterable as its argument. This avoids converting map(frozenset,List_2) into a set and therefore gains some performance.
out = [*map(list,{*map(frozenset,List_1)}.symmetric_difference(map(frozenset,List_2)))]

Convert list of list into single list [duplicate]

This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 3 years ago.
Currently I have a list of lists
l=[['asd'],['fgd']].
I want to turn it into a list
goal_list=['asd','fgd']
but I do not know how to turn a list into the value inside it - does anyone have an idea how to this efficiently?
This is a perfect use-case for itertools.chain, where we essentially chain all sublists together to flatten them!
from itertools import chain
def single_list(arr):
return list(chain(*arr))
print(single_list([['asd'],['fgd']]))
print(single_list([['asd', 'abcd'],['fgd', 'def']]))
The output will be
['asd', 'fgd']
['asd', 'abcd', 'fgd', 'def']
Just use a list comprehension with two loops:
goal_list = [item for sublist in l for item in sublist]

How to convert a python list containing several lists into single list? [duplicate]

This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 6 years ago.
How do I convert a list of lists to a single list?
Input:
a=[['AA'], ['AE'], ['AH'], ['AO'],]
Desired output:
['AA','AE','AH','AO']
a=[['AA'], ['AE'], ['AH'], ['AO'],]
l=[]
for i in a:
l.extend(i)
print l
you could use comprehension list:
or using map and lambda functions
a=[['AA'], ['AE'], ['AH'], ['AO'],]
# open the item [0] with generators
Newa = [x[0] for x in a]
>>>['AA', 'AE', 'AH', 'AO']
see examples: http://www.secnetix.de/olli/Python/list_comprehensions.hawk
EDIT:
for i, value in enumerate(a):
a[i] = value[0]

Iterating through two list and appending the items together [duplicate]

This question already has answers here:
How do I iterate through two lists in parallel?
(8 answers)
Closed 7 years ago.
So I need to append two list together. Each element of the List one attached to each element of List two. So it the final list will be something like this: ['L1[0]L2[0]','L1[1]L2[1]','L1[2]L2[2]','L1[3]L2[3]']. I keep running into the problem of putting a for loop inside another for loop but the result is having the first loop element repeat multiple times. I understand this isn't working, if any one can give me a nudge or somewhere to look into information on this sort of subject. As always thank you for the help!! Here is my code:
def listCombo(aList):
myList=['hello','what','good','lol','newb']
newList=[]
for a in alist:
for n in myList:
newList.append(a+n)
return newList
Example:
List1=['florida','texas','washington','alaska']
List2=['north','south','west','east']
result= ['floridanorth','texassouth','washingtonwest','','alaskaeast']
You need to use zip.
[i+j for i,j in zip(l1, l2)]
Example:
>>> List1=['florida','texas','washington','alaska']
>>> List2=['north','south','west','east']
>>> [i+j for i,j in zip(List1, List2)]
['floridanorth', 'texassouth', 'washingtonwest', 'alaskaeast']
list comprehension over zip:
[x[0]+x[1] for x in zip(list1,list2)]
>>> [x[0]+x[1] for x in zip(['1','2','3'],['3','4','5'])]
# ['13', '24', '35']

Categories

Resources