I have a list:
[55, 41, 45, 43, 60, 47, 33, 70, 42, 42, 44]
I would like to create a new list which ranks these items in the order they are:
Expected Output:
[7, ,2 ,9 ,10, 4, 11, 3, 6, 1, 5, 8]
Tried these 3 version of the func but its not working properly, not sure why?
def argsort(seq):
#return sorted(range(len(seq)), key = seq.__getitem__)
#return [i for (v, i) in sorted((v, i) for (i, v) in enumerate(seq))]
return [x for x,y in sorted(enumerate(seq), key = lambda x: x[1])]
returns:
[6, 1, 8, 9, 3, 10, 2, 5, 0, 4, 7]
Let's come up with a more precise definition of what you are after:
Given a list L of numbers, create a list M that contains the valid indices of L, such that M[i] is the index at which the ith element of L occurs, when sorted. Present M as if the first element of L occurs at index 1.
Now, there are two ways of the valid indices of a list:
range(len(L)): gives a sequence of numbers 0... len(L)-1
enumerate(L): gives a sequence of tuples (0, L[0])... (len(L)-1, L[len(L)-1])
Since you want to operate under the assumption that list indices start at 1 (when in fact they start at 0 in python), we need to do a little off-setting
range(len(L)) becomes `range(1, len(L)+1)
enumerate(L) becomes enumerate(L, 1) (the optional argument tells enumerate to start numbering at 1)
Since we need the list items as well, let's use enumerate, rather than use range and do a lookup (I personally prefer this method, though both are valid)
So now, we can get a list of tuples, in which each tuple contains the index of an element in L and the corresponding element in L. We need to sort this by the elements themselves. This can be done with a call to sorted, with the optional key argument explaining that we should sort by the second element of the tuple (operator.itemgetter(1) says exactly this).
Once we have a sorted list of such tuples, all we need to do is extract the first element of each tuple (the index in L), we can use the list-comprehension [i[0] for i in mylist], or equivalently [operator.itemgetter(0)(t) for t in mylist]
Putting all these elements together, we get the following
In [138]: L = [55, 41, 45, 43, 60, 47, 33, 70, 42, 42, 44]
In [139]: [operator.itemgetter(0)(t) for t in sorted(enumerate(L,1), key=operator.itemgetter(1))]
Out[139]: [7, 2, 9, 10, 4, 11, 3, 6, 1, 5, 8]
Related
My goal with this is to generate the sum of each sublist separately using nested loops
This is my list called sales_data
sales_data = [[12, 17, 22], [2, 10, 3], [5, 12, 13]]
The sublist can be represented by any variable but for the purpose of this exercise, we will call it scoops_sold, which I have set to 0
scoops_sold = 0
So far I am able to run the nested loop as follows
sales_data = [[12, 17, 22], [2, 10, 3], [5, 12, 13]]
scoops_sold = 0
for location in sales_data:
for element in location:
scoops_sold += element
print(scoops_sold)
This gives me 96 as the result
What I essentially want to accomplish is to return the sum of each sublist but I am not sure I might be able to do that. I thought about using slicing but that was not effective
You can easily solve it using sum():
print(list(map(sum, sales_data)))
If you insist on loops:
sums = []
for location in sales_data:
sold = 0
for element in location:
sold += element
sums.append(sold)
print(sums)
How about
[sum(sub_list) for sub_list in sales_data]
# [51, 15, 30]
However, the question is a bit confusing because you are setting scoops_sold to 0, an int, when the result you describe is a list of int.
If you want to have the sum of all subsets, you might want to use a list to store each subsets' sum, and by using the built-in python function sum, you just need to use one loop:
scoops_sold = []
for sale_data in sales_data:
salscoops_solds_sum.append(sum(sale_data))
The same result can be achieved in one line by using list comprehensions:
scoops_sold = [sum(sale_data) for sale_data in sales_data]
sales_data = [[12, 17, 22], [2, 10, 3], [5, 12, 13]]
scoops_sold = 0
for location in sales_data:
print(location)
for element in location:
scoops_sold += element
print(scoops_sold)
I have two array
arr_1 = [2, 4, 6, 32]
arr_2 = [56, 45, 12, 65]
I am tying to give user_input from 'arr_1 list'
e.g. if I choose to give user_input '32' from 'arr_1 list', it should shuffle '32' to any position in 'arr_1 list' and along with '32' the element from 'arr_2 list' which is in same position that is '65' should also be shuffle. I tried many ways, but it shuffles all elements from a list using random.shuffle.
from random import randint
def shuffle_them(arr_1, arr_2, element_to_remove):
# get the index where to be removed element is
index_to_remove = arr_1.index(element_to_remove)
# remove that element
arr_1.remove(element_to_remove)
# randomly generate the new index
new_index = randint(0, len(arr_1))
# insert the removed element into that position in array 1
arr_1.insert(new_index, element_to_remove)
# also change the position of elements in array 2 accordingly
arr_2[new_index], arr_2[index_to_remove] = arr_2[index_to_remove], arr_2[new_index]
We find the index of element that user wants moving. Then we remove it. Then we generate a new index for it and insert it there. Lastly we use the original index and new index to exchange the values in the second array.
usage
# before
arr_1 = [2, 4, 6, 32]
arr_2 = [56, 45, 12, 65]
# shuffiling
shuffle_them(arr_1, arr_2, element_to_remove=32)
# after (32 and 65 places changed in same way)
> arr_1
[2, 32, 4, 6]
> arr_2
[56, 65, 12, 45]
another round
# before
arr_1 = [2, 4, 6, 32]
arr_2 = [56, 45, 12, 65]
# shuffiling
shuffle_them(arr_1, arr_2, element_to_remove=6)
# after (6 and 12 places changed in same way)
> arr_1
[2, 4, 32, 6]
> arr_2
[56, 45, 65, 12]
note: function directly mutates the mutable arr_1 and arr_2. It doesn't return new lists.
I have list a = [1,2,3,6,8,12,13,18,33,23] and list b=[] that is empty. I need each value in list a compare with all the values in the list b by taking the difference of the new value from list a with all the contents of the list b. If the difference is grater than to the value of the threshold, it must insert to list b rather than skip to the next value in a, how can do that?
a =[1,2,3,6,8,12,13,18,33,23]
b=[]
b.append(a[0])
for index in range(len(a)):
for i in range(len(b)):
x = a[index] - b[i]
if x > 1:
b.append(a[index])
print("\nOutput list is")
for v in range(len(b)):
print(b[v])
The desired output is:
output = [1,6,8,12,18,33,23]
To further clarify, in first time the list b have the first item from list a. I need to check if the a[0]-b[0]>1, then insert the value of a[0] in b list, and next if a[1] - b[0]>1 then insert the a[1] in b list , and if [[a[2] -b[0] >1] and [a[2]-b[1] > 1]] then insert a[2] in b list and so on
Here is the probable solution to the stated problem though the output is not matching with your desired outcome. But sharing on the basis of how I understood the problem.
a = [1, 2, 3, 6, 8, 12, 13, 18, 33, 23]
b = []
b.append(a[0])
threshold = 1 # Set Threshold value
for index in range(len(a)):
difference = 0
for i in range(len(b)):
difference = abs(a[index] - b[i])
if difference > threshold:
continue # Keep comparing other values in list b
else:
break # No need for further comparison
if difference > threshold:
b.append(a[index])
print("\nOutput list is")
print(b)
Output is:
Output list is
[1, 3, 6, 8, 12, 18, 33]
Also, I notice that after swapping the last two elements (33 <-> 23 ) of the list a as below:
a = [1, 2, 3, 6, 8, 12, 13, 18, 23, 33]
and running the same code. the output was near to your desired output:
Output list is
[1, 3, 6, 8, 12, 18, 23, 33]
This problem is very interesting now as I put myself into more investigation. And I found it a very interesting. Let me explain. First consider the list a as a list of integer numbers starting from 1 to N. For example:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
and set the threshold to 1
threshold = 1 # Set Threshold value
Now, run the programme with threshold = 1 and you will get the output:
Output list is
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
and if you rerun with threshold = 2, you will get the following output:
threshold = 2
Output list is
[1, 4, 7, 10, 13, 16, 19]
Basically, this programme is basically generating a hopping series of integer numbers where hopping is set to the threshold value.
Interesting!!! Isn't it???
I have a dictionary of values in tuple form, how to get the values in list form.
I want to get values from the tuples and create new lists and create another 3 lists with squares from them.
dictionary={1:(1,2,3),2:(3,4,5),3:(6,7,8),4:(9,10,11),5:(12,13,14)}
s=list(d.values())
d=[item for t in s for item in t]
print(d)
I used list comprehension i got this output:
[1, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Using list comprehension
Expected_output:
[1,3,6,9,12],
[2,4,7,10,13],
[3,5,8,11,14],
squares**2 output above three list :
[1,9,36,81,144],
[4,16,49,100,169],
[9,25,64,121,196]
Provided with a Dictionary
First take a empty list and assign it to a variable “l”
Using list comprehension separate the values and store that in a variable
Iterate the values and append the empty list “l”
Now iterate the “l” using index values i[o], i[1], i[2] and store in various variables respectively
Using map function square the variables and store the values and print them using the list of variables
x = {
1:(1,2,3),
2:(4,5,6),
3:(7,8,9),
4:(10,11,12),
5:(13,14,15)
}
l = []
y = [i for i in x.values()]
for i in y:
l.append(i)
print(l)
m = [i[0] for i in l]
n = [i[1] for i in l]
o = [i[2] for i in l]
m1 = map(lambda i:i**2, m)
n1 = map(lambda i:i**2, n)
o1 = map(lambda i:i**2, o)
print(m)
print(list(m1))
print(n)
print(list(n1))
print(o)
print(list(o1))
you can use zip to collect the index elements of each list together, then use list comprehension to square them
dictionary={1:(1,2,3),2:(3,4,5),3:(6,7,8),4:(9,10,11),5:(12,13,14)}
list_vals = list(zip(*dictionary.values()))
squares = [[num ** 2 for num in nums] for nums in list_vals]
print(list_vals)
print(squares)
OUTPUT
[(1, 3, 6, 9, 12), (2, 4, 7, 10, 13), (3, 5, 8, 11, 14)]
[[1, 9, 36, 81, 144], [4, 16, 49, 100, 169], [9, 25, 64, 121, 196]]
Thanks to comments from #roganjosh highlighting that the dict will only be assured to be ordered if the pythong version is 3.6 or higher. If your python version is less than that you would first need to sort the values by order of the keys. Below is an example.
dictionary={2:(3,4,5),3:(6,7,8),4:(9,10,11),5:(12,13,14),1:(1,2,3)}
ordered_key_val = sorted(dictionary.items(), key=lambda items: items[0])
list_vals = list(zip(*[val for key, val in ordered_key_val]))
squares = [[num ** 2 for num in nums] for nums in list_vals]
print(list_vals)
print(squares)
You can use numpy to transpose the entire list once the values of the dictionary are obtained. You can use the below program
import numpy as np
dictionary={1:(1,2,3),2:(3,4,5),3:(6,7,8),4:(9,10,11),5:(12,13,14)}
list_out= []
for i in dictionary.keys():
list_out.append(dictionary[i])
tran_list = np.transpose(list_out)
out_list = tran_list*tran_list
Output of this is:
>>> out_list
array([[ 1, 9, 36, 81, 144],
[ 4, 16, 49, 100, 169],
[ 9, 25, 64, 121, 196]])
This is an array output! Anyway if you want it only in the list, ofcourse , you can play with it!
You can do this way:
>>> temp = list(zip(*dictionary.values()))
>>> [list(i) for i in temp]
[[1, 3, 6, 9, 12], [2, 4, 7, 10, 13], [3, 5, 8, 11, 14]]
>>> [[i**2 for i in elem] for elem in temp]
[[1, 9, 36, 81, 144], [4, 16, 49, 100, 169], [9, 25, 64, 121, 196]]
I have one dictionary here
d={1:(1,2,3),2:(4,5,6),3:(7,8,9),4:(10,11,12),5:(13,14,15)}
first I want to get values in tuple in three lists then I used list comprehension here The below code gives the tuple values in three lists
myList1 = [d [i][0] for i in (d.keys()) ]
print(myList1)
myList2 = [d [i][1] for i in (d.keys()) ]
print(myList2)
myList3 = [d [i][2] for i in (d.keys()) ]
print(myList3)
Here all the tuple values converted into list form
[1, 4, 7, 10, 13]
[2, 5, 8, 11, 14]
[3, 6, 9, 12, 15]
Now I want to squares the elements in three lists here I Used lambda expression the below code squares the elements in the lists
a1= list(map(lambda x: x**2 ,myList1))
print(a1)
a2= list(map(lambda x: x**2 ,myList2))
print(a2)
a3= list(map(lambda x: x**2 ,myList3))
print(a3)
The output is:
[1, 16, 49, 100, 169]
[4, 25, 64, 121, 196]
[9, 36, 81, 144, 225]
I have a list, a = [5, 4, 9, 3, 6, 6, 8, 2], and I essentially want to sum the first three numbers, and that sum will be the first value in the new list. The next value in the new list will be the sum of 4, 9, and 3...etc. etc. How to loop this in Python?
list slicing is a good method.
all you need to do is travese from start index to end index-2 , ( can make sum of last 3 element and when you reach second last or last ement you wont be able to take 3 elemnts)
here you can take 3 elemnts and using list slicing, slice list from the
current index to next 3 index ie a[i:i+3] where [i,i+3) is range. then on that new list performing sum operation and appending the reuslt to final list.
a = [5, 4, 9, 3, 6, 6, 8, 2]
res=[]
for i in range(len(a)-2):
res.append(sum(a[i:i+3]))
print(res)
output
[18, 16, 18, 15, 20, 16]
One liner:
list(map(sum, zip(a, a[1:], a[2:])))
Output:
[18, 16, 18, 15, 20, 16]
So you are creating the required sublists of the numbers you want to add up and then you sum each sublist using the high-order function map.
If I understood what you want:
b = [sum(a[i : i+3]) for i in range(0, len(a)-2)]