I'm trying to find the indexes of all the elements in a python list of lists. The list would look something like this:
list = [[x,y,x],
[x,y,y],
[y,y,y]]
To do this I have tried to use a nested loop like this:
for lst in list:
print(list.index(lst))
for x in lst:
print(lst.index(x))
This however prints out a long list with almost seemingly random numbers.
screenshot of output for a slightly different list
What I'm tring to achieve is an output looking something like this:
0
1
0
2
0
3
1
0
1
0
Is there anyone who can help out a python beginner?
You can enumerate to print indexes
x = 22
y = 34
l = [[x,y,x],
[x,y,y],
[y,y,y]]
indexes = [(i, j) for i, nl in enumerate(l) for j, nle in enumerate(nl)]
print(*indexes, sep="\n")
# output
(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(1, 2)
(2, 0)
(2, 1)
(2, 2)
https://docs.python.org/3/library/functions.html#enumerate
You can easily access index and value with the use of by looping thorugh the list using enumerate. I added some printing with text to show what number is what.
myList = [[1,2,3],
[4,5,6],
[7,8,9]]
for lstIdx, lst in enumerate(myList):
print("list idx: " + str(lstIdx))
for idx, item in enumerate(lst):
print("item idx in list: " + str(idx))
output:
list idx: 0
item idx in list: 0
item idx in list: 1
item idx in list: 2
list idx: 1
item idx in list: 0
item idx in list: 1
item idx in list: 2
list idx: 2
item idx in list: 0
item idx in list: 1
item idx in list: 2
Related
For example, I have 2 lists:
list1 = [6,6,6,6,6,6,6]
list2 = [0,2,4]
If there are the same indexes in the list1 and list2, I need to remove these indexes from the list1, because I should sum the unique indexes from the list1, for example:
a = [1,2,3,4,5]
b = [0,2,4]
x = [a.index(i) for i in a]
y = [b.index(j) for j in b]
for idx in y:
if idx in x:
x.remove(idx)
print(sum(x))
printed is >> 7
I tried this but did not work if there are the same values in list1
a = [6,6,6,6,6,6,6]
b = [0,2,4]
x = [a.index(i) for i in a]
y = [b.index(j) for j in b]
for idx in y:
if idx in x:
x.remove(idx)
printed is >> 0
Indexes and values are different. There will never be the same index twice in one list. You get their index by their value, however index(value) function gives you the first index which matches your value. Have a look at:
a, b, x = [1,2,3,4,5,6,7], [1,2,3], 0
c, d = len(a), len(b)
if d < c:
d, c = len(a), len(b)
for i in range(c, d):
x += i
print(x)
Your question is not very clear, so here are two answers:
If you want to sum the elements from the first list that do not appear in the second list, here is a way to do it:
a = [1,2,3,4,5]
b = [0,2,4]
# We create a set in order to have O(1) operations to check if an element is in b
b_set = set(b)
# We sum on the values of a that are not in b
res = sum(x for x in a if x not in b_set)
print(res)
>>> 9
If you want to sum the elements of the first list that do not have their rank/index in the second list, a way to do that could be:
a = [1,2,3,4,5]
b = [0,2,4]
# We create a set in order to have O(1) operations to check if an element is in b
b_set = set(b)
# We sum on the values of a that don't have their rank/index in b
res = sum(x for (i, x) in enumerate(a) if i not in b_set)
print(res)
>>> 6
If there is arr = [1, 2, 3] so len(arr) is 3 right?
for i in range(0, len(arr)+1):
print(arr[i])
It is no secret that you can not do that, simply IndexError: list index out of range.
So how is this possible?
def max_sequence(arr):
if arr:
li = []
x = {sum(arr[i:j]): arr[i:j] for i in range(0, len(arr))
for j in range(1, len(arr)+1)}
li.append(max(x.items()))
for ii in li:
print(ii)
return li[0][0]
else:
return 0
print(max_sequence([26, 5, 3, 30, -15, -7, 10, 20, 22, 4]))
I simply had to find the maximum sum of a contiguous subsequence in a list of integers.
If I write this part:
x = {sum(arr[i:j]): arr[i:j] for i in range(0, len(arr))
for j in range(1, len(arr))}
It shows that maximum sum is 94, that is incorrect.
If I write this:
x = {sum(arr[i:j]): arr[i:j] for i in range(0, len(arr))
for j in range(1, len(arr)+1)}
Maximum sum is 98, it is correct. But why is so? If I write "for j in range(1, len(arr)+1)" why there is no IndexError?
We can generate a sequence of numbers using range() function. Range(10) will generate numbers from 0 to 9 (10 numbers).
We can also define the start, stop and step size as range(start, stop,step_size).
Here in your example, "for j in range(1, len(arr)+1)"
len(arr) is 10.
So range will generate numbers from 1 to 10.
Also, your li is an empty array so its length can be varied. You are storing the result i.e. the sum in li array as well as it will store the original array and this j will help it to store it.
I created a program to get the the max value of a list and the position of its occurrences (list starting at indexing with 1 not 0) but I can't manage to find any useful solutions.
The input is always a string of numbers divided by zero.
This is my code:
inp = list(map(int,input().split()))
m = max(inp)
count = inp.count(m)
print(m)
def maxelements(seq): # #SilentGhost
return [i for i, j in enumerate(seq) if j == m]
print(maxelements(inp))
I expect to output the maximum value and then all the positions of its occurrences. (also is it possible to do without brackets as in the example below?)
Input: 4 56 43 45 2 56 8
Output: 56
2 6
If you want to shift index values, you could just do
return [i + 1 for i, j in enumerate(seq) if j == m]
more generally any transformation of i or j!
def f(i, j):
# do whatever you want, and return something
return i + 1
return [f(i, j) for i, j in enumerate(seq) if j == m]
Without brackets, as a string:
return " ".join(str(i + 1) for i, j in enumerate(seq) if j==m)
Specifiy start=1 with enumerate():
>>> l = [4, 56, 43, 45, 2, 56, 8]
>>> max_num = max(l)
>>> [i for i, e in enumerate(l, start=1) if e == max_num]
[2, 6]
By default enumerate() uses start=0, because indices start at 0.
I am solving a problem on Hackerrank and I'm using a dictionary as:
dic = {'1':type1, '2':type2, '3':type3, '4',type4, '5',type5}
In my problem, I need to return the key which has the maximum value (type variables are counts of each type).
Like if the value of type4 is 3 (type4 count is 3) then I need to return the key '4'.
How do I do that?
I tried using keys() and items() functions but they return lists and not particular elements.
type1 = 0
type2 = 0
type3 = 0
type4 = 0
type5 = 0
maxim = 0
for i in arr:
if i == 1:
type1+=1
elif i == 2:
type2+=1
elif i == 3:
type3+=1
elif i == 4:
type4+=1
else:
type5+=1
dic = {'1':type1, '2':type2, '3':type3, '4':type4, '5':type5}
for j in range(1,len(dic)):
if dic[str(j)]>maxim:
maxim = dic[str(j)]
return maxim
My output comes out to be 3 which is the maximum count that one of the type variables hold but what I need is for it to return the key to the corresponding value (here value is 3 and key is 4).
Your code cleaned up would lead to:
arr = [1,2,3,2,3,4,5,3,4,21,1,2,3,2,3,4,5,6,5,4,3,2,3,4,1,1,1,2]
dic = {}
for i in arr:
dic.setdefault(i,0) # set count of 0 if not existent
dic[i] +=1 # increase count
# use the builtin max function to get the item with the highest count
m = max(dic.items(), key = lambda x:x[1])
print(m) # (3,7)
See dict.setdefault
Using a collections.Counter will speed this up, it is a specialized dict to count things:
from collections import Counter
arr = [1,2,3,2,3,4,5,3,4,21,1,2,3,2,3,4,5,6,5,4,3,2,3,4,1,1,1,2]
# feed the array into Counter (which is a specialized counting dictionary)
c = Counter( arr )
print(c.most_common())
key, occ = c.most_common()[0]
print( key,"occured",occ,"times")
Output:
# counter.most_common() - i.e. 3 occured 7 time, 2 occured 6 times etc. it is sorted
[(3, 7), (2, 6), (1, 5), (4, 5), (5, 3), (6, 1), (21, 1)]
3 occured 7 times
I have a list initialized:
best_selected = [[2, 3, 0, 1], [1, 3, 0, 2], [1, 2, 3, 0], [1, 0, 2, 3]]
0 1 2 3
finalList = [[0, 1308, 17410, 16098], [1246, 0, 17557, 16244], [17675, 18002, 0, 5618], [16257, 16584, 5508, 0]]
0 1 2 3
The finalList as a matrix looks like this:
[[ 0 1308 17410 16098]
[ 1246 0 17557 16244]
[17675 18002 0 5618]
[16257 16584 5508 0]]
What I'm trying to do is to iterate in every list of best_selected and add them depending on which index it is in on the other list. And lets say in the first iteration is [2, 3, 0, 1] in best_selected list. The first element in the list is 2 so I'm going to start in :
[[ 0 1308 17410 16098]
[ 1246 0 17557 16244]
--> [17675 18002 0 5618]
[16257 16584 5508 0]]
Since the next number of 2 is 3 respectively in the first iteration of the best_selected, so I would get 5618 as the first value to be in the index. Since it stopped at 3 I would now check next at:
[[ 0 1308 17410 16098]
[ 1246 0 17557 16244]
[17675 18002 0 5618]
--> [16257 16584 5508 0]]
As the next element of 3 is 0*, then I would try to add 16257 in the variable 'index' that contained the value 5618 so the index would now contain the value of 16257 + 5618. I'm trying to do that in each of every iteration of best_selected and so far I'm having errors
The code I'm trying to work out:
count = len(best_selected)
index = 0
j = 0
val = best_selected[0]
while count != 0:
index = index + finalList[best_selected[val]]
if counter == 1:
pass
else:
val = best_selected[j+1]
j = j + 1
counter = counter - 1
print(index)
Any fix or an easy solution would highly be appreciated!
If I understand you correctly, you want a sliding window of the current item and the next item in the sublist. You could just iterate over the sublists and then over the range range(len(sublist)-1), so that you can assign the first index to i = sublist[indx] and the second to j = sublist[indx+1].
index = 0
for sublist in best_selected:
for indx in range(len(sublist)-1):
i = sublist[indx]
j = sublist[indx+1]
index += finalList[i][j]
The nicer variant would be to zip the sublist with sublist[1:] to get tuples with the indices which you can immediately unpack in the head of the loop:
for sublist in best_selected:
for i, j in zip(sublist, sublist[1:]):
index += finalList[i][j]
Here's the solution with the separate sublist sums:
sums = []
for sublist in best_selected:
sublist_sum = 0
for i, j in zip(sublist, sublist[1:]):
sublist_sum += finalList[i][j]
sums.append(sublist_sum)
print(sums)
print(sum(sums))