I want to find the index of max values in a nested list:
For example the nested list is:
[[15 16 18 19 12 11] [13 19 23 21 16 12] [12 15 17 19 20 10] [10 14 16 13 9 6]]
the max values should be 19, 23, 20, 16.
I also want to find their index in tuple format such as
19: (0,3) 23:(1,2) 20: (2,4)
I know how to find the global maximum of the nested list, but not sure how to find the max values for each list.
You just need a for loop to solve this.
I'll give you a real answer, but you will want to look into this more to understand what is going on:
for ii,line in enumerate(data):
max_val = max(line)
index = line.index(max_val)
print("{}:({},{})".format(max_val,ii,index),end=' ')
print()
a for loop in python is going to give you each element in an iterable. In this case you've got a list-of-lists, so each line is going to be a list. Since you want those numbered, I've put the data inside the enumerate function, which returns a pair of (,<element) which the for loop unpacks into the variables ii and line.
The next line max_val is assigned by the max function which returns the maximum value in the iterable line.
The index variable is set by the method list.index of the line list instance, which returns the first index of the value given to it in the list the method is called on.
Finally I print the output in the format you want by using a string and calling the format method to fill in the {} placeholders. more information on format strings can be found here. Also, the print function defaults to a newline after each print; so rather than introduce string-building here, I changed the end-line to a space and added an extra print after the for-loop to get you a new-line.
There's a lot here, and I can see how you might be lost on this question. I'm going to link to each of the built-in commands I used here so that you can learn more about python's "batteries included" functions and methods.
for-loop flow control
Built-in functions:
enumerate
max
print
Python built-in data structures
lists
Happy hacking.
to solve your problem, i'd probably go with a dictionary comprehension (which is actually working the same way as list comprehensions)
{max(nested_list): (i, nested_list.index(max(nested_list))) for i, nested_list in enumerate(your_list_of_list)}
Using the enumerate python built-in function allows you to get both the index of the nested list (i) and its value (nested_list).
From there, you can easily find the maximum of each nested list with the max function.
Finally, the index method allows you to find the first occurence of the maximum value from the nested list.
Related
l = [1,2,3,[4,5,6]]
I want
l = [1,2,3,[4,5,6,7]]
Now I want to add 7 in the list which is inside the list.
I applied the same logic as accessing [3][3]
l.insert("index","value") #syntax
l.insert([3][3],7)
But it isn't working. I couldn't solve it with append as well.
You want to add a 7 to the element at index 3 in l.
That is:
l[3].append(7)
you can do the following:
l[3].insert(3,7)
What's wrong with your approach? In the insert(index, value) method the index should be an integer. The [3][3] you are passing, is not an integer. Moreover, it is not even a valid value (meaning, you can't write eg x = [3][3].
The [i] after an object calls its __getitem__ method internally. So, what you are trying to do is
get the element 3 of the initial list
hope that what you get is a list
insert on position 3 of that list
So, you can do that
inner_list = mylist[3]
inner_list.insert(3, 7)
or, more compactly mylist[3].insert(3, 7)
If you want to insert at the last position, you could as well write mylist[3].append(7)
Here l[3][3] is an int. Ofcouse it will not work as there are no built-ins defined such as insert and append on int
While l[3] is of list type so it supports both of those functions
l[3].append(7) or l[3].insert(3,7)
Also lists are mutable type so making a change in inner list will be reflected in the outer list as well. Hope it helps
you can access to that 7 with:
l[3][3]
What I have:
A dataframe as the following
I.D Score
1 11 26
3 12 26
5 13 26
6 14 25
multiply a million rows....
What I am trying to do:
1) Pass both columns to a function called Points and create a list called players. credits to #jezrael
players = [Points(int(a),b) for a, b in zip(score['I.D'],score['Score'])]
2) Pass the list to another basic function, that simply uploads the whole list
upload_to_scoreboard(players)
What I get
MemoryError
I believe that passing the whole list consisting of million rows to the next function causes it to run out of memory. how can I modify the code to pass the list to the upload_to_scoreboard without causing memory error?
Use generator instead of list.
To do so replace [] by () to surround your list comprehension.
players = [Points(int(a),b) for a, b in zip(score['I.D'],score['Score'])] loads the entire list in memory. To avoid it you can use a generator. Generators are kind of list but with the difference that every item is computed and loaded in memory only when it is itered, and it is unloaded once you no longer use it.
However in your case, the upload_to_score_board function must accept a such data structure and don't use list specificities.
To know more about generators vs list, read this : https://medium.freecodecamp.org/python-list-comprehensions-vs-generator-expressions-cef70ccb49db#741d
Trying to find the index of a sublists with an element. I’m not sure how to specify the problem exactly (which may be why I’ve overlooked it in a manual), however my problem is thus:
list1 = [[1,2],[3,4],[7,8,9]]
I want to find the first sub-list in list1 where 7 appears (in this case the index is 2, but lll could be very very long). (It will be the case that each number will appear in only 1 sub-list – or not at all. Also these are lists of integers only)
I.e. a function like
spam = My_find(list1, 7)
would give spam = 2
I could try looping to make a Boolean index
[7 in x for x in lll]
and then .index to find the 'true' - (as per Most efficient way to get indexposition of a sublist in a nested list)
However surely having to build a new boolean list is really inefficient..
My code starts with list1 being relatively small, however it keeps building up (eventually there will be 1 million numbers arranged in approx. 5000 sub-lists of list1
Any thoughts?
I could try looping to make a Boolean index
[7 in x for x in lll]
and then .index to find the 'true' … However surely having to build a new boolean list is really inefficient
You're pretty close here.
First, to avoid building the list, use a generator expression instead of a list comprehension, by just replacing the [] with ().
sevens = (7 in x for x in lll)
But how do you do the equivalent of .index when you have an arbitrary iterable, instead of a list? You can use enumerate to associate each value with its index, then just filter out the non-sevens with filter or dropwhile or another generator expression, then next will give you the index and value of the first True.
For example:
indexed_sevens = enumerate(sevens)
seven_indexes = (index for index, value in indexed_sevens if value)
first_seven_index = next(seven_indexes)
You can of course collapse all of this into one big expression if you want.
And, if you think about it, you don't really need that initial expression at all; you can do that within the later filtering step:
first_seven_index = next(index for index, value in enumerate(lll) if 7 in value)
Of course this will raise a StopIteration exception instead of a ValueError expression if there are no sevens, but otherwise, it does the same thing as your original code, but without building the list, and without continuing to test values after the first match.
This is part of my code:
add_values=[2,5,10,20,50,100,200,500,1000,2000,5000,10000,20000,50000]
for each in add_values:
print(each)
s=add_values[each]
s=int(s)
h=s*100
mydict[add_values[each]]=s
And it is bringing up this error:
IndexError: list index out of range
(For the s=add_values[each] line)
Please can you tell what is wrong here and what needs changing,
Thanks.
Think about reaching the fifth item in add_values:
for each in add_values:
print(each) # each == 50
s=add_values[each] # what's the fiftieth item in 'add_values'?!
You don't need to index into add_values, you are already accessing the value - replace add_values[each] with, simply, each.
each is the value, you can't use it as an index (mainly because the size of add_values is 14 and you have values that are greater than this inside add_values):
add_values=[2,5,10,20,50,100,200,500,1000,2000,5000,10000,20000,50000]
for each in add_values:
print(each)
s=each
s=int(s)
h=s*100
mydict[each]=s
Another solution would be to use an index:
add_values=[2,5,10,20,50,100,200,500,1000,2000,5000,10000,20000,50000]
for i in range(len(add_values)):
print(add_values[i])
s=add_values[i]
s=int(s)
h=s*100
mydict[add_values[i]]=s
You are using an array element as an array index, which is why you are getting an out-of-bounds error.
With Python's for loop notation, you don't need to access an index explicitly; just access the element, which in your case is each:
for each in add_values:
print(each)
s=each # kind of redundant, but this should work
for each in add_value sets each to 2, 5, 10, 20, 50, etc. On the 4th iteration of the loop, each is 20. When you say add_values[each], you get an error because add_values has only 14 elements and you're trying to access element number 20. You'd get in even more trouble if it tried to access element number 50000.
I have an ordered dictionary like following:
source =([('a',[1,2,3,4,5,6,7,11,13,17]),('b',[1,2,3,12])])
I want to calculate the length of each key's value first, then calculate the sqrt of it, say it is L.
Insert L to the positions which can be divided without remainder and insert "1" after other number.
For example, source['a'] = [1,2,3,4,5,6,7,11,13,17] the length of it is 9.
Thus sqrt of len(source['a']) is 3.
Insert number 3 at the position which can be divided exactly by 3 (eg. position 3, position 6, position 9) if the position of the number can not be divided exactly by 3 then insert 1 after it.
To get a result like folloing:
result=([('a',["1,1","2,1","3,3","4,1","5,1","6,3","7,1","11,1","13,3","10,1"]),('b',["1,1","2,2","3,1","12,2"])]
I dont know how to change the item in the list to a string pair. BTW, this is not my homework assignment, I was trying to build a boolean retrival engine, the source data is too big, so I just created a simple sample here to explain what I want to achive :)
As this seems to be a homework, I will try to help you with the part you are facing problem with
I dont know how to change the item in the list to a string pair.
As the entire list needs to be updated, its better to recreate it rather than update it in place, though its possible as lists are mutable
Consider a list
lst = [1,2,3,4,5]
to convert it to a list of strings, you can use list comprehension
lst = [str(e) for e in lst]
You may also use built-in map as map(str,lst), but you need to remember than in Py3.X, map returns a map object, so it needs to be handled accordingly
Condition in a comprehension is best expressed as a conditional statement
<TRUE-STATEMENT> if <condition> else <FALSE-STATEMENT>
To get the index of any item in a list, your best bet is to use the built-in enumerate
If you need to create a formatted string expression from a sequence of items, its suggested to use the format string specifier
"{},{}".format(a,b)
The length of any sequence including a list can be calculated through the built-in len
You can use the operator ** with fractional power or use the math module and invoke the sqrt function to calculate the square-root
Now you just have to combine each of the above suggestion to solve your problem.