it's very easy to get the number of items in a list, len(list), but say I had a matrix like:
[[1,2,3],[1,2,3]]
Is there a pythonic way to return 6? Or do I have to iterate.
You can use chain
from itertools import chain
l = [[1,2,3],[1,2,3]]
len(list(chain(*l))) # give you 6
the expression list(chain(*l)) give you flat list: [1, 2, 3, 1, 2, 3]
Make the matrix numpy array like this
mat = np.array([[1,2,3],[1,2,3]])
Make the array 1D like this
arr = mat.ravel()
Print length
print(len(arr))
l = [[1,2,3],[1,2,3]]
len([item for innerlist in l for item in innerlist])
gives you 6
You just need to flatten list.
Numpy is the best option.
Still if you want, you can use simple if/else to flatten and return length of list.
Example,
list_1 = [1, 2, 3, 'ID45785', False, '', 2.85, [1, 2, 'ID85639', True, 1.8], (e for e in range(589, 591))]
def to_flatten3(my_list, primitives=(bool, str, int, float)):
flatten = []
for item in my_list:
if isinstance(item, primitives):
flatten.append(item)
else:
flatten.extend(item)
return len(flatten)
print(to_flatten3(list_1))
14
[Program finished]
Related
Suppose, I have a list [0.5,1,1.5,2,2.5,3,3.5,4,4.5], now I would like to extract the indices of a list [1.5,2.5,3.5,4.5], which is a subset of that list.
You can use the inbuilt function <list>.index to find the index of each element(of second list) in the first list.
Having that learnt, you can use list comprehension to achieve what you want:
>>> list1 = [0.5,1,1.5,2,2.5,3,3.5,4,4.5]
>>> list2 = [1.5,2.5,3.5,4.5]
>>> [list1.index(elem) for elem in list2]
[2, 4, 6, 8]
One other option is to use enumerate function. See the following answer:
a = [0.5,1,1.5,2,2.5,3,3.5,4,4.5]
b = [1.5,2.5,3.5,4.5]
indexes = []
for id, i in enumerate(a):
if i in b:
indexes.append(id)
print(indexes)
The output is going to be [2, 4, 6, 8].
List comprehensions are often cited as an elegant way to iterate through list of lists, like [item for sublist in original_list for item in sublist].
However to me it seem to only deal with simple list of lists that has 2 layers: [[1,2],[3,4].
Is there an universal elegant way to find an item in unknown number of layers of list of lists?
[0,[1,[2,[3]]],[4,[5]],6].
I have thought about flattening all the elements into a single list before checking, but any simpler methods?
If you don't want to flatten the array, you can use recursion to iterate over a list and recurs on each another list inside it.
Code:
def check(lst, x):
for i in range(len(lst)):
if type(lst[i]) == list: # If there is another list inside it
if check(lst[i], x): # If the value x exist in lst[i]
return True
elif lst[i] == x: # If there is no more list inside it
return True
return False # X can't be found in lst.
print(check([0, [1, [2, [3]]], [4, [5]], 6], 5)) # Output: True
print(check([0, [1, [2, [3]]], [4, [5]], 6], 9)) # Output: False
If you want to check if an element exists in the list, you must flatten it first, as below, then search for it in the flattened list
from pandas.core.common import flatten
lis = [0,[1,[2,[3]]],[4,[5]],6]
new_lis = list(flatten(lis))
print(new_lis)
// [0, 1, 2, 3, 4, 5, 6]
print(6 in new_lis)
// True
I'm doing some Google Python Class exercises and I'm trying to find a pythonic solution to the following problem.
D. Given a list of numbers, return a list where all adjacent ==
elements have been reduced to a single element, so [1, 2, 2, 3]
returns [1, 2, 3]. You may create a new list or modify the passed in
list.
My try, which is working perfectly is the following:
def remove_adjacent(nums):
result = []
for num in nums:
if len(result) == 0 or num != result[-1]:
result.append(num)
return result
For example, with remove_adjacent([2, 2, 3, 3, 3]) the output is [2, 3]. Everything's ok.
I'm trying to use list comprehensions in order to archieve this in a more pythonic way, so my try is the following:
def remove_adjacent(nums):
result = []
result = [num for num in nums if (len(result)==0 or num!=result[-1])]
return result
This, with the same input [2, 2, 3, 3, 3], the output is [2, 2, 3, 3, 3] (the same). Meeeh! Wrong.
What I'm doing wrong with the list comprehensions? Am I trying to do something which is impossible to do with list comprehensions? I know it's a bit weird to initialize the list (result = []), so maybe it's not posible to do it using list comprehensions in this case.
Am I trying to do something which is impossible to do with list comprehensions?
Yep. A list comprehension can't refer to itself by name, because the variable doesn't get bound at all until the comprehension is completely done evaluating. That's why you get a NameError if you don't have result = [] in your second code block.
If it's not cheating to use standard modules, consider using groupby to group together similar values in your list:
>>> import itertools
>>> seq = [1, 2, 2, 3]
>>> [k for k,v in itertools.groupby(seq)]
[1, 2, 3]
>>> seq = [2,2,3,3,3]
>>> [k for k,v in itertools.groupby(seq)]
[2, 3]
For the sake of learning, I'd suggest using core reduce function:
def remove_adjacent(lst):
return reduce(lambda x, y: x+[y] if not x or x[-1] != y else x, lst, [])
Let's say I have 2 arrays inside a single array, like:
main_array = [[1, 2, 3, 4], [4, 5, 6, 7]]
I would like to find the min and max of each of those arrays and store them in a single array. For the above it would be:
result = [1, 4, 4, 7]
How do I use Python's inbuilt min() and max() in this case?
I tried min(main_array) and max(main_array) but that is giving me:
result = [1,7]
You can just use min() or max() on single list to get it's min/max value. You can also use list comprehension to loop through lists in list and functions you want to use:
main_array = [[1,2,3,4], [4,5,6,7]]
res = [func(l) for l in main_array for func in (min, max)]
print(res)
main_array = [[1, 2, 3, 4], [4, 5, 6, 7]]
result = []
for inner_list in main_array:
result.append(min(inner_list))
result.append(max(inner_list))
Probably the more readable way to do it is:
result = []
for list in main_array:
result.append(min(list))
result.append(max(list))
print(result)
Try
main_array = [[1,2,3,4],[4,5,6,7]]
out = []
for arr in main_array:
out.extend([min(arr), max(arr)])
print(out)
You need to iterate over each of the sub arrays and call min and max on that.
You could also use generators
def minthenmax(arr):
for i in arr:
yield min(i)
yield max(i)
print(list(minthenmax(main_array)))
First off you're missing a common on the definition of your main array...
main_array = [[1,2,3,4],[4,5,6,7]]
To get the min of the first sub-array.
min(main_array[0])
...and the max...
max(main_array[0])
Hopefully you can work out the rest from this.
In one line. You can use build-in map function to map two inner lists to min function and then max function. Finally you can concatenate them.
map(min, main_array) + map(max, main_array)
main_array = [[1,2,3,4],[4,5,6,7]]
x = min(main_array[0]), max(main_array[0])
y = min(main_array[1]), max(main_array[1])
new_array = [i for i in x + y]
print (new_array)
output:
[1, 4, 4, 7]
You've got to search for min and max on each item of lst.
lst = [[1,2,3,4],[4,5,6,7]]
m = []
for k in lst: m.append([min(k), max(k)])
=> [[1, 4], [4, 7]]
I just want simple list which remove duplicate digit
a = [2,3,4,4,4,4,5,6,7,8,9,9,9,9,0]
m = []
def single_digit_list(a):
return [m.append(x) for x in a if x not in m]
print "New List", single_digit_list(a)
I was expected that new list gave me the one digit in list not repeated but i got following output
New List [None, None, None, None, None, None, None, None, None]
I can't understand what going on
Simple Know what is wrong in code
use set to remove duplicates:
m=set(a)
If you wanted output to be list:
m=list(set(a) )
Your code is good..You just have to return m...instead of returning return value of append...For ex, print m.append(10) will print None which is actually append's return value,you are not printing m.
You could modify you code as follows to return list:
a = [2,3,4,4,4,4,5,6,7,8,9,9,9,9,0]
def single_digit_list(a):
m = []
[m.append(x) for x in a if x not in m]
return m #you have appended elements to m
You are trying to return a list of lists where all the lists are None.
This is because m.append() does not return anything and you are trying to create a list of what m.append returns
Just do it as:
def single_digit_list(a):
m = []
for x in a:
if x not in m:
m.append(x)
return m
>>> print single_digit_list([2,3,4,4,4,4,5,6,7,8,9,9,9,9,0])
[2,3,4,5,6,7,8,9,0]
If your list is already grouped, you can use groupby.
>>> x = [1, 1, 4, 4, 4, 5, 2, 2, 2, 3, 3]
>>> from itertools import groupby
>>> print [i[0] for i in groupby(x)]
[1, 4, 5, 2, 3]
This solution does not break order of element instead of converting to set.
The reason why you got list of None value is :
List comprehension is use to generate a list base on the return of the expression given inside the list comprehension.
Eg: [ expression for item in list if conditional ]
So, in your case you are appending an item into a list, which return None after appending the item if it was appending successfully.
Eg:
>>> ls = []
>>> print ls.append('a')
None
>>>
So, at the end of your list comprehension, your list m got the correct unique element list but you return the list generate by the comprehension which is a list of None value.
Conclusion:
You can fix that by return the value of m not the result of list comprehension.
Or here is another easy solution using dictionary key:
>>> a = [2,3,4,4,4,4,5,6,7,8,9,9,9,9,0]
>>> dict.fromkeys(a).keys()
[0, 2, 3, 4, 5, 6, 7, 8, 9]
>>>