I want to compare elements in same list and append to other list but I have some problems.
For example:
a=[3,4,21,36,10,28,35,5,24,42]
c=[]
I want to do this:
4>3 append to other list.
21>4 append to other list.
36>21 append to other list.
28>10 but don't append this to other list because 36 is bigger than 28.
The result should be c=[4,21,36,42].
I tried this code:
b=0
d=1
while len(a)>b and len(a)>d:
if a[d]>a[b]:
c.append(a[d])
b+=1
d+=1
But it instead gives me:
c=[4, 21, 36, 28, 35, 24, 42]
Try this :
a=[3,4,21,36,10,28,35,5,24,42]
c = []
for x in range(1,len(a)):
count = 0
for y in range(x):
if a[x] > a[y]:
count = count + 1
if count == x:
c.append(a[x])
print(c)
you can iterate and check
currentList = [3,4,21,36,10,28,35,5,24,42]
newList = []
current_low = currentList[0]-1 # initialse current_low as [(first element of list) - 1]
for value in currentList:
if value > current_low:
newList.append(value)
current_low = value
>>>print(newList)
[3, 4, 21, 36, 42]
It took a moment to realize you want numbers that are less than ALL previous numbers, not just the number before it.
If you want to do this with a list comprehension, you could do:
c = [a[i] for i in range(1,len(a)) if a[i] > max(a[:i])]
Result: [4, 21, 36, 42]
If, however, you changed your mind and decided you wanted numbers greater than their previous number, you could do:
c = [j for (i,j) in filter(lambda x: x[0] < x[1], zip(a, a[1:]))]
Result: [4, 21, 36, 28, 35, 24, 42]
The objective of task required to produce an array output such that output[i] is equal to the sum of all the elements of nums except nums[i].
Eg: given [6,7,8,9], return [24,23,22,21].
Input = [6,7,8,9]
The calculation behind is
0+7+8+9 = 24
6+0+8+9 = 23
6+7+0+9 = 22
6+7+8+0 = 21
Output = [ 24, 24, 22, 21 ]
You can use list comprehension:
In [1]: a = [6,7,8,9]
In [2]: s = sum(a)
In [3]: [s - i for i in a]
Out[3]: [24, 23, 22, 21]
Use numpy broadcasting + vectorised operations for this:
import numpy as np
x = np.array([6,7,8,9])
y = np.sum(x) - x
# array([24, 23, 22, 21])
You can use a for loop and python's inbuilt sum function
a = [6,7,8,9] #your input array
b = [] # initialise an empty list
for index in range(len(a)): #iterate through the list's length
b.append( sum( a[0:index] + a[index+1:] ) ) #add to two parts before and
# after the index
print(b)
Is it possible to do the below with list comprehension? Trying to store the maximum value that has been seen at any given point through the loop.
def test(input):
a = input[0]
b = []
for i in input:
a = max(i,a)
b.append(a)
return b
print test([-5,6,19,4,5,20,1,30])
# returns [-5, 6, 19, 19, 19, 20, 20, 30]
You can use itertools.accumulate with the max builtin in Python 3:
from itertools import accumulate
lst = [-5,6,19,4,5,20,1,30]
r = list(accumulate(lst, max)) #[i for i in accumulate(lst, max)]
print(r)
# [-5, 6, 19, 19, 19, 20, 20, 30]
What you present here is a typical form of what is known in functional programming as scan.
A way to do this with list comprehension that is inefficient is:
[max(input[:i]) for i in range(1,n+1)]
But this will run in O(n2).
You can do this with list comprehension given you use a function with side effects: like the following:
def update_and_store(f,initial=None):
cache = [initial]
def g(x):
cache[0] = f(cache[0],x)
return cache[0]
return g
You can then use:
h = update_and_store(max,a[0])
[h(x) for x in a]
Or you can use a dictonaries setdefault() like:
def update_and_store(f):
c = {}
def g(x):
return c.setdefault(0,f(c.pop(0,x),x))
return g
and call it with:
h = update_and_store(max)
[h(x) for x in a]
like #AChampion says.
But functions with side-effects are rather unpythonic and not declarative.
But you better use a scanl or accumulate approach like the one offered by itertools:
from itertools import accumulate
accumulate(input,max)
If using NumPy is permitted, then you can use NumPy:
import numpy as np
np.maximum.accumulate([-5,6,19,4,5,20,1,30])
# array([-5, 6, 19, 19, 19, 20, 20, 30])
I'm using list comprehension with the for loop but what I'm looking for is: from a for loop get two lists .
Example (it's obviously not working but I want something like that):
def f(i): return i*i
def g(i): return 1.0/(1+i*i)
seq1, seq2=[(f(i),g(i))
for i in xrange(10)]
The result what I'm looking for has to be :
seq1= [f(0),f(1),..,f(9)]
seq2= [g(0),g(1),..,g(9)]
Is there a feasible solution?
Thanks in advance!
Yes, your update clarified (and simplified) things — and here's my updated answer written to work in both Python 2 & 3:
try:
from itertools import izip
except ImportError: # Python 3
izip = zip
xrange = range
def f(i): return i*i
def g(i): return 1.0/(1+i*i)
seq1, seq2 = map(list, izip(*[(f(i), g(i)) for i in xrange(10)]))
print(' i ' + ' '.join(('{:5d}'.format(i) for i in xrange(10))))
print('seq1 = [' + ', '.join(('{:5d}'.format(v) for v in seq1)) + ']')
print('seq2 = [' + ', '.join(('{:.3f}'.format(v) for v in seq2)) + ']')
Output:
i 0 1 2 3 4 5 6 7 8 9
seq1 = [ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
seq2 = [1.000, 0.500, 0.200, 0.100, 0.059, 0.038, 0.027, 0.020, 0.015, 0.012]
What you want to do can be done, but it is not too much transparent...
In practice, you create a list of tuples and later you unpack the
tuples in two (three, etc) using zip(*
Using zip returns tuples, if you absolutely need lists you have to
jump through another hoop...
>>> def f(i): return i*i
>>> def g(i): return 1.0/(1+i*i)
>>> t1, t2 = zip(*[(f(i),g(i+1)) for i in range(5)])
>>> l1, l2 = map(list, zip(*[(f(i),g(i+1)) for i in range(5)]))
>>> print t1, t2
(0, 1, 4, 9, 16) (0.5, 0.2, 0.1, 0.058823529411764705, 0.038461538461538464)
>>> print l1, l2
[0, 1, 4, 9, 16] [0.5, 0.2, 0.1, 0.058823529411764705, 0.038461538461538464]
>>>
I have a list:
a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50,
35, 41, 49, 37, 19, 40, 41, 31]
max element is 55 (two elements on position 9 and 12)
I need to find on which position(s) the maximum value is situated. Please, help.
a.index(max(a))
will tell you the index of the first instance of the largest valued element of list a.
>>> m = max(a)
>>> [i for i, j in enumerate(a) if j == m]
[9, 12]
The chosen answer (and most others) require at least two passes through the list.
Here's a one pass solution which might be a better choice for longer lists.
Edited: To address the two deficiencies pointed out by #John Machin. For (2) I attempted to optimize the tests based on guesstimated probability of occurrence of each condition and inferences allowed from predecessors. It was a little tricky figuring out the proper initialization values for max_val and max_indices which worked for all possible cases, especially if the max happened to be the first value in the list — but I believe it now does.
def maxelements(seq):
''' Return list of position(s) of largest element '''
max_indices = []
if seq:
max_val = seq[0]
for i,val in ((i,val) for i,val in enumerate(seq) if val >= max_val):
if val == max_val:
max_indices.append(i)
else:
max_val = val
max_indices = [i]
return max_indices
I came up with the following and it works as you can see with max, min and others functions over lists like these:
So, please consider the next example list find out the position of the maximum in the list a:
>>> a = [3,2,1, 4,5]
Using the generator enumerate and making a casting
>>> list(enumerate(a))
[(0, 3), (1, 2), (2, 1), (3, 4), (4, 5)]
At this point, we can extract the position of max with
>>> max(enumerate(a), key=(lambda x: x[1]))
(4, 5)
The above tells us, the maximum is in the position 4 and his value is 5.
As you see, in the key argument, you can find the maximum over any iterable object by defining a lambda appropriate.
I hope that it contributes.
PD: As #PaulOyster noted in a comment. With Python 3.x the min and max allow a new keyword default that avoid the raise exception ValueError when argument is empty list. max(enumerate(list), key=(lambda x:x[1]), default = -1)
Also a solution, which gives only the first appearance, can be achieved by using numpy:
>>> import numpy as np
>>> a_np = np.array(a)
>>> np.argmax(a_np)
9
I can't reproduce the #SilentGhost-beating performance quoted by #martineau. Here's my effort with comparisons:
=== maxelements.py ===
a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50,
35, 41, 49, 37, 19, 40, 41, 31]
b = range(10000)
c = range(10000 - 1, -1, -1)
d = b + c
def maxelements_s(seq): # #SilentGhost
''' Return list of position(s) of largest element '''
m = max(seq)
return [i for i, j in enumerate(seq) if j == m]
def maxelements_m(seq): # #martineau
''' Return list of position(s) of largest element '''
max_indices = []
if len(seq):
max_val = seq[0]
for i, val in ((i, val) for i, val in enumerate(seq) if val >= max_val):
if val == max_val:
max_indices.append(i)
else:
max_val = val
max_indices = [i]
return max_indices
def maxelements_j(seq): # #John Machin
''' Return list of position(s) of largest element '''
if not seq: return []
max_val = seq[0] if seq[0] >= seq[-1] else seq[-1]
max_indices = []
for i, val in enumerate(seq):
if val < max_val: continue
if val == max_val:
max_indices.append(i)
else:
max_val = val
max_indices = [i]
return max_indices
Results from a beat-up old laptop running Python 2.7 on Windows XP SP3:
>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_s(me.a)"
100000 loops, best of 3: 6.88 usec per loop
>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_m(me.a)"
100000 loops, best of 3: 11.1 usec per loop
>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_j(me.a)"
100000 loops, best of 3: 8.51 usec per loop
>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_s(a100)"
1000 loops, best of 3: 535 usec per loop
>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_m(a100)"
1000 loops, best of 3: 558 usec per loop
>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_j(a100)"
1000 loops, best of 3: 489 usec per loop
You can also use the numpy package:
import numpy as np
A = np.array(a)
maximum_indices = np.where(A==max(a))
This will return an numpy array of all the indices that contain the max value
if you want to turn this to a list:
maximum_indices_list = maximum_indices.tolist()
a = [32, 37, 28, 30, 37, 25, 27, 24, 35,
55, 23, 31, 55, 21, 40, 18, 50,
35, 41, 49, 37, 19, 40, 41, 31]
import pandas as pd
pd.Series(a).idxmax()
9
That is how I usually do it.
>>> max(enumerate([1,2,3,32,1,5,7,9]),key=lambda x: x[1])
>>> (3, 32)
#shash answered this elsewhere
A Pythonic way to find the index of the maximum list element would be
position = max(enumerate(a), key=lambda x: x[1])[0]
Which does one pass. Yet, it is slower than the solution by #Silent_Ghost and, even more so, #nmichaels:
for i in s m j n; do echo $i; python -mtimeit -s"import maxelements as me" "me.maxelements_${i}(me.a)"; done
s
100000 loops, best of 3: 3.13 usec per loop
m
100000 loops, best of 3: 4.99 usec per loop
j
100000 loops, best of 3: 3.71 usec per loop
n
1000000 loops, best of 3: 1.31 usec per loop
Just one line:
idx = max(range(len(a)), key = lambda i: a[i])
Here is the max value and the indexes it appears at:
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50, 35, 41, 49, 37, 19, 40, 41, 31]
>>> for i, x in enumerate(a):
... d[x].append(i)
...
>>> k = max(d.keys())
>>> print k, d[k]
55 [9, 12]
Later: for the satisfaction of #SilentGhost
>>> from itertools import takewhile
>>> import heapq
>>>
>>> def popper(heap):
... while heap:
... yield heapq.heappop(heap)
...
>>> a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50, 35, 41, 49, 37, 19, 40, 41, 31]
>>> h = [(-x, i) for i, x in enumerate(a)]
>>> heapq.heapify(h)
>>>
>>> largest = heapq.heappop(h)
>>> indexes = [largest[1]] + [x[1] for x in takewhile(lambda large: large[0] == largest[0], popper(h))]
>>> print -largest[0], indexes
55 [9, 12]
Similar idea with a list comprehension but without enumerate
m = max(a)
[i for i in range(len(a)) if a[i] == m]
If you want to get the indices of the largest n numbers in a list called data, you can use Pandas sort_values:
pd.Series(data).sort_values(ascending=False).index[0:n]
You can do it in various ways.
The old conventional way is,
maxIndexList = list() #this list will store indices of maximum values
maximumValue = max(a) #get maximum value of the list
length = len(a) #calculate length of the array
for i in range(length): #loop through 0 to length-1 (because, 0 based indexing)
if a[i]==maximumValue: #if any value of list a is equal to maximum value then store its index to maxIndexList
maxIndexList.append(i)
print(maxIndexList) #finally print the list
Another way without calculating the length of the list and storing maximum value to any variable,
maxIndexList = list()
index = 0 #variable to store index
for i in a: #iterate through the list (actually iterating through the value of list, not index )
if i==max(a): #max(a) returns a maximum value of list.
maxIndexList.append(index) #store the index of maximum value
index = index+1 #increment the index
print(maxIndexList)
We can do it in Pythonic and smart way! Using list comprehension just in one line,
maxIndexList = [i for i,j in enumerate(a) if j==max(a)] #here,i=index and j = value of that index
All my codes are in Python 3.
Here's a simple single-pass solution.
import math
nums = [32, 37, 28, 30, 37, 25, 55, 27, 24, 35, 55, 23, 31]
max_val = -math.inf
res = []
for i, val in enumerate(nums):
if(max_val < val):
max_val = val
res = [i]
elif(max_val == val):
res.append(i)
print(res)
import operator
def max_positions(iterable, key=None, reverse=False):
if key is None:
def key(x):
return x
if reverse:
better = operator.lt
else:
better = operator.gt
it = enumerate(iterable)
for pos, item in it:
break
else:
raise ValueError("max_positions: empty iterable")
# note this is the same exception type raised by max([])
cur_max = key(item)
cur_pos = [pos]
for pos, item in it:
k = key(item)
if better(k, cur_max):
cur_max = k
cur_pos = [pos]
elif k == cur_max:
cur_pos.append(pos)
return cur_max, cur_pos
def min_positions(iterable, key=None, reverse=False):
return max_positions(iterable, key, not reverse)
>>> L = range(10) * 2
>>> L
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> max_positions(L)
(9, [9, 19])
>>> min_positions(L)
(0, [0, 10])
>>> max_positions(L, key=lambda x: x // 2, reverse=True)
(0, [0, 1, 10, 11])
This code is not as sophisticated as the answers posted earlier but it will work:
m = max(a)
n = 0 # frequency of max (a)
for number in a :
if number == m :
n = n + 1
ilist = [None] * n # a list containing index values of maximum number in list a.
ilistindex = 0
aindex = 0 # required index value.
for number in a :
if number == m :
ilist[ilistindex] = aindex
ilistindex = ilistindex + 1
aindex = aindex + 1
print ilist
ilist in the above code would contain all the positions of the maximum number in the list.