I am trying to get 25 Numbers to put them in a 2D list/array but whenever i try to get the index of the item, I'm always facing a valueError.
What i tried.
I have tried using a for loop with the enumerate() function to get the specfic Item which is (1).
I have also tried using the .index() method but also with that I was faced with a ValueError: 1 is not in the list. Which made me confused as to why the code isn't working.
mylist = [list(map(int, input().split())),
list(map(int, input().split())),
list(map(int, input().split())),
list(map(int, input().split())),
list(map(int, input().split())),]
print(mylist)
print(mylist.index(1))
Here is one approach to consider:
myList = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [12, 3, 5, 6, 7], [2, 4, 5, 6, 7], [2, 4, 3, 6, 2]]
def index_2d(input_list, value):
for i, row in enumerate(input_list):
try:
return (i, row.index(value))
except ValueError:
continue
# You can also raise ValueError here instead of implicit return (un-comment the next line)
# raise ValueError(f'{value} is not in the list')
Output:
>>> print(myList)
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [12, 3, 5, 6, 7], [2, 4, 5, 6, 7], [2, 4, 3, 6, 2]]
>>> print(index_2d(myList, 12))
(2, 0)
>>> print(index_2d(myList, 11))
None
Explanation:
We accept the 2d-list and a value we are trying to check. Then use enumerate (to keep track of the index of the main array). We then use index() at each row (list in the main array) to check if the value belongs there, if not (ValueError exception got raised) we simply move to the next row and repeat. But if index() resolves, we return a tuple of the index of the list inside the main list (from the enumerate()) and the index inside the second list or row.
Related
lst = [1, 4, 5, 9, 6]
How to write a code to get some missing values which must return [2, 3, 7, 8]?
Here is my code
new_list = []
for i in range(1, len(lst1)):
if i not in lst1:
new_list.append(i)
print(new_list)
You can convert them to sets and use "-" to calculate the difference. Note that the order is important.
You need to define what you want to compare your list to if you want to find the missing elements. You can automatically do this if it is simple like "the numbers from 1 to 10" using the code:
list(range(1, 10))
The comparison code is:
lst1 = [1, 4, 5, 9, 6]
lst2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
out = list(set(lst2) - set(lst1))
print(out)
which returns
[8, 2, 3, 7]
It isn't clear exactly what you want from your question, if you give a more detail it will be easier to help.
My_list= [[1,2,3],[4,5,6],[7,8,9]] āāā-> [[1,2,3],[6,5,4],[7,8,9]]
I tried using this with out success :
for i my_list:
if my_list.index(i) != 0:
i = i[::-1]
Since Python for loops create local variables, you have to index into the outer list indexes and use % 2 == 1 to detect sublists with odd indexes.
my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
for index, sublist in enumerate(my_list):
if index % 2 == 1:
my_list[index] = sublist[::-1]
print(my_list)
Outputs
[[1, 2, 3], [6, 5, 4], [7, 8, 9], [12, 11, 10]]
Another option (in addition to #DeepSpace answer) is using Python's slicing notation (link) and assigning to slice (link):
In this example, we create slice starting from index 1 and step 2 and assign reverse sublist to it:
my_list = [[1,2,3],[4,5,6],[7,8,9]]
my_list[1::2] = (v[::-1] for v in my_list[1::2])
print(my_list)
Prints:
[[1, 2, 3], [6, 5, 4], [7, 8, 9]]
I am confused about what does lists[outer_index][inner_index] do? I thought that when two lists are next to each other, it means the first list is the selected list and the second list indicates the index of the first list. However, that doesn't seem to be the case here.
def flatten(lists):
results = []
for outer_index in range(len(lists)): # outer index = 0, 1
for inner_index in range(len(lists[outer_index])): # inner_index = [0, 1, 2, 0, 1, 2, 3, 4, 5]
results.append(lists[outer_index][inner_index])
return results
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
print(flatten(n))
You are creating an list of lists (basically a table).
n = [[1, 2, 3],
[4, 5, 6, 7, 8, 9]]
If I do n[0][1] I am saying go to row 0 and grab the element in column 1.
Its better to think of it this way.
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
s = n[0] # Now s = [1,2,3], the first element in n
s[1] = 2 # Because I just grabbed the second element in [1,2,3]
# This is the same as
n[0][1]
How to merge two array and group by key?
Example:
my_list = [3, 4, 5, 6, 4, 6, 8]
keys = [1, 1, 2, 2, 3, 5, 7]
Expected outcome:
[[1, 3, 4], [2, 5, 6], [3, 4], [5, 6], [7, 8]]
If I understand it right, the list of keys map to the list of values. You can use the zip function to iterate through two lists at the same time. Its convenient in this case. Also check up on the beautiful defaultdict functionality - we can use it to fill a list without initialising it explicitely.
from collections import defaultdict
result = defaultdict(list) # a dictionary which by default returns a list
for key, val in zip(keys, my_list):
result[key].append(val)
result
# {1: [3, 4], 2: [5, 6], 3: [4], 5: [6], 7: [8]}
You can then go to a list (but not sure why you would want to) with:
final = []
for key, val in result.items():
final.append([key] + val) # add key back to the list of values
final
# [[1, 3, 4], [2, 5, 6], [3, 4], [5, 6], [7, 8]]
I think you have to write it by your own using set() to remove duplicates, so I have made a function called merge_group
my_list = [3, 4, 5, 6, 4, 6, 8]
keys = [1, 1, 2, 2, 3, 5, 7]
def merge_group(input_list : list, input_key : list):
result = []
i = 0
while i < len(my_list):
result.append([my_list[i], keys[i]])
i += 1
j = 0
while j < len(result):
if j+1 < len(result):
check_sum = result[j] + result[j+1]
check_sum_set = list(set(check_sum))
if len(check_sum) != len(check_sum_set):
result[j] = check_sum_set
j += 1
return result
print(merge_group(my_list, keys))
I have an assignment to do, which is:
Write a function transpose which takes in a matrix and transposes it. Basically, this converts a m x n matrix into a n x m matrix.
I wrote a code which seems sensible, but it doesnt get me the result I want. Can anyone point out what is wrong with my code?
def transpose(matrix):
new_matrix=[[]]*len(matrix[0])
for row in matrix:
i=0
for j in row:
new_matrix[i]+=[j]
i+=1
return new_matrix
Test case:
print(transpose([[ 1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]))
If you use the * to multiply some values in a list-initialisation, be careful. You might end up with references that point multiple times to the same value:
l = [ [] ]*3
print(l)
l[1].append(34) # change only "the first" list by appending smth
print(l)
Output:
[[], [], []]
[[34], [34], [34]] # they are all "the same data" reference
There is an built-in zip() that does exactly your transposing:
l = [[ 1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
l_t = [ list(x) for x in zip(*l)] # one-line solutions for transposing ;)
print(l)
print(l_t) # transposed
Zip has the limitation that it only works to the length of the smallest sublists - yours are all equal so all is fine.
Output:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
If you ever need a zip that takes the longest list, itertools.zip_longest(..) can be used, it takes a default param that is substituted for any shorter list-items that are not there.
Btw. just list(zip(l)) looks like this: [(1,5,9),(2,6,10),(3,7,11),(4,8,12)] - it create tuples over the same indexes of the parts of the iterable you put into it.
By hand:
l = [[ 1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
l2 = []
for colIdx in range(len(l[0])): # 0-3 iterate over the inner indexes first
newRow = []
for rowIdx in range(len(l)): # 0-2 then over the outer ones
newRow.append(l[rowIdx][colIdx])
l2.append(newRow)
print(l2) # [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
What i meant was something like this:
def t(array): #The original array has size mxn
duplicate = [[0 for x in range(len(array))] for y in range(len(array[1]))] #You create an array of size nxm, which is filled with zeros
for i in range(len(array)): #Loop over the rows
for j in range(len(array[i])): #Then loop over the columns
duplicate[j][i] = array[i][j] #Replace j,i or duplicate with i,j th element of original
return duplicate
Now,
>>> t([[ 1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]