I have a double nested list. I would like to remove the second element inside of the nested list. i.e. [[[x,1],[x,2],[x,3]],[[x,1],[x,2],[x,3]]] - python-3.x

for x in y:
[z.pop(0) for z in x]
IndexError: pop index out of range.
The function seems to keep looping after it has gone through all the values of x. I would like to move on the next value of x after it has done it has completed its work. I understand that the error is occurring due to the changing of my data shape, but how do I avoid this?

First solution:
nested_list = [[[11,1],[20,2],[300,3]],[[100,1],[202,2],[303,3]]]
for lst in nested_list:
for j in lst:
j.pop(1)
print(nested_list)
The above solution will give you the following output:
[[[11], [20], [300]], [[100], [202], [303]]]
Second Solution
nested_list = [[[11,1],[20,2],[300,3]],[[100,1],[202,2],[303,3]]]
result = []
for lst in nested_list:
for j in lst:
result.append(j[0])
print(result)
del nested_list
The above solution will give you the following output:
[11, 20, 300, 100, 202, 303]
If you are familiar with python then you can also go with the following:
nested_list = [[[11,1],[20,2],[300,3]],[[100,1],[202,2],[303,3]]]
def return_first(lst):
return [j[0] for i in lst for j in i]
print(return_first(nested_list))
del nested_list
The above solution will give you the following output:
[11, 20, 300, 100, 202, 303]

Related

Why does this list return [False, False, 3, True]?

I've been working through an exercise on Kaggle and was tasked with: Return a list with the same length as L, where the value at index i is True if L[i] is greater than thresh, and False otherwise.
L = [1, 2, 3, 4]
LL = L
for nums in L:
if L[nums] > 2:
LL[nums] = True
else:
LL[nums] = False
print(LL)
That is what I came up with but it prints the list [False, False, 3, True]. Also, I replaced the variable "thresh" with the number 2 and added a print instead of a return statement since it's not a function. I'm guessing that this result is because when it hits the 3 or the number in index #2 in the list it for some reason skips over it and I cannot seem to figure out why?
Problem:
Your for loop is wrong. You are using nums as if it were an index in the array; the problem is that the in keyword in Python gives you the actual items from the list, which in this case are the numbers themselves. For example:
my_list = [5,3,1,6]
for num in my_list:
print(num)
# prints 5,3,1,6
Also, you should create a deep copy of the original list so that you don't overwrite the original list:
LL = L.copy()
Hint: if based on this, you understand what's wrong, try to implement it correctly before reading the solution below!
Solution:
The correct way to implement this:
L = [1, 2, 3, 4]
LL = L.copy() # this creates an actual copy, not just a reference
for i in range(len(L)):
if L[i] > 2:
LL[i] = True
else:
LL[i] = False
print(LL)

How to delete certain element(s) from an array?

I have a 2d array, how can I delete certain element(s) from it?
x = [[2,3,4,5,2],[5,3,6,7,9,2],[34,5,7],[2,46,7,4,36]]
for i in range(len(x)):
for j in range(len(x[i])):
if x[i][j] == 2:
del x[i][j]
This will destroy the array and returns error "list index out of range".
you can use pop on the list item. For example -
>>> array = [[1,2,3,4], [6,7,8,9]]
>>> array [1].pop(3)
>>> array
[[1, 2, 3, 4], [6, 7, 8]]
I think this can solve your problem.
x = [[2,3,4,5,2],[5,3,6,7,9,2],[34,5,7],[2,46,7,4,36]]
for i in range(len(x)):
for j in range(len(x[i])):
if j<len(x[i]):
if x[i][j] == 2:
del x[i][j]
I have tested it locally and working as expected.Hope it will help.
Mutating a list while iterating over it is always a bad idea. Just make a new list and add everything except those items you want to exclude. Such as:
x = [[2,3,4,5,2],[5,3,6,7,9,2],[34,5,7],[2,46,7,4,36]]
new_array = []
temp = []
delete_val = 2
for list_ in x:
for element in list_:
if element != delete_val:
temp.append(element)
new_array.append(temp)
temp = []
x = new_array
print(x)
Edit: made it a little more pythonic by omitting list indices.
I think this is more readable at the cost of temporarily more memory usage (making a new list) compared to the solution that Sai prateek has offered.

Python: Use a for loop to get Nth number out of a list

I need to get every 3rd value out of a list and add it to a new list.
This is what I have so far.
def make_reduced_samples(original_samples, skip):
skipped_list = []
for count in range(0, len(original_samples), skip):
skipped_list.append(count)
return skipped_list
skip is equal to 3
I get the indexes and not the value of the numbers in the list.
It gives me [0,3,6]. Which are the indexes in the list and not the value of the indexes.
The example I am given is:
In this list [12,87,234,34,98,11,9,72], you should get [12,34,9].
I cannot use skipped_list = original_samples[::3] in any way.
You need to append the value of the original_samples array at the index. Not the index (count) itself.
def make_reduced_samples(original_samples, skip):
skipped_list = []
for count in range(0, len(original_samples), skip):
skipped_list.append(original_samples[count])
return skipped_list
The correct, most pythonic, and most efficient way to do that is to use slicing.
lst = [12, 87, 234, 34, 98, 11, 9, 72]
skipped_list = lst[::3]
print(skipped_list) # [12, 34, 9]
If the step does not obey a linear relation (which it does here), then you could use a list-comprehension with enumerate to filter on the index.
skipped_list = [x for i, x in enumerate(lst) if i % 3 == 0]
print(skipped_list) # [12, 34, 9]
One liner:
skipped_list = [j for (i,j) in enumerate(original_samples, start=1) if i % 3 == 0]

Using python need to get the substrings

Q)After executing the code Need to print the values [1, 12, 123, 2, 23, 3, 13], but iam getting [1, 12, 123, 2, 23, 3]. I have missing the letter 13. can any one tell me the reason to overcome that error?
def get_all_substrings(string):
length = len(string)
list = []
for i in range(length):
for j in range(i,length):
list.append(string[i:j+1])
return list
values = get_all_substrings('123')
results = list(map(int, values))
print(results)
count = 0
for i in results:
if i > 1 :
if (i % 2) != 0:
count += 1
print(count)
Pretty straight forward issue in your nested for loops within get_all_substrings(), lets walk it!
You are iterating over each element of your string 123:
for i in range(length) # we know length to be 3, so range is 0, 1, 2
You then iterate each subsequent element from the current i:
for j in range(i,length)
Finally you append a string from position i to j+1 using the slice operator:
list.append(string[i:j+1])
But what exactly is happening? Well we can step through further!
The first value of i is 0, so lets skip the first for, go to the second:
for j in range(0, 3): # i.e. the whole string!
# you would eventually execute all of the following
list.append(string[0:0 + 1]) # '1'
list.append(string[0:1 + 1]) # '12'
list.append(string[0:2 + 1]) # '123'
# but wait...were is '13'???? (this is your hint!)
The next value of i is 1:
for j in range(1, 3):
# you would eventually execute all of the following
list.append(string[1:1 + 1]) # '2'
list.append(string[1:2 + 1]) # '23'
# notice how we are only grabbing values of position i or more?
Finally you get to i is 2:
for j in range(2, 3): # i.e. the whole string!
# you would eventually execute all of the following
list.append(string[2:2 + 1]) # '3'
I've shown you what is happening (as you've asked in your question), I leave it to you to devise your own solution. A couple notes:
You need to look at all index combinations from position i
Dont name objects by their type (i.e. dont name a list object list)
I would try something like this using itertools and powerset() recipe
from itertools import chain, combinations
def powerset(iterable):
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))
output = list(map(''.join, powerset('123')))
output.pop(0)
Here is another option, using combinations
from itertools import combinations
def get_sub_ints(raw):
return [''.join(sub) for i in range(1, len(raw) + 1) for sub in combinations(raw, i)]
if __name__ == '__main__':
print(get_sub_ints('123'))
>>> ['1', '2', '3', '12', '13', '23', '123']

Python - Insert value to list in a dictionary

I need your help to fix my code. I try to append a value to a list in a dictionary.
def distance(x1, y1, x2, y2):
dis=((x1-x2)**2) + ((y1-y2)**2)
return dis
def cluster_member_formation2(arrCH, arrN, k):
dicCH = dict.fromkeys(arrCH,[])
arrE = []
for j in range(len(arrCH)):
d_nya = distance(arrN[1][0], arrN[1][1], arrN[arrCH[j]][0], arrN[arrCH[j]][1])
arrE.append(d_nya)
minC = min(arrE)
ind = arrE.index(minC)
x = arrCH[ind]
dicCH[x].append(1)
print(arrE, minC, ind, x, dicCH)
arrCH=[23, 35]
arrN={0:[23, 45, 2, 0], 1:[30,21,2,0], 23:[12, 16, 2, 0], 35:[48, 77, 2, 0]}
cluster_member_formation2(arrCH, arrN, 1)
The output:
[349, 3460] 349 0 23 {35: [1], 23: [1]}
I try to calculate the distance between node 1 and all node in arrCH, and then take the minimum distance. In the output show the result of arrE is [349, 3460], so the minimum is 349. 349 has index 0, then I find arrCH with index 0, likes arrCH[0]=23. Finally, I want update dicCH[23].append(1) so the result is
{35: [], 23: [1]}
But, why my code update the all keys, 35 and 23?
I hope someone can help me.
Thank you..
classmethod fromkeys(seq[, value])
Create a new dictionary with keys
from seq and values set to value.
All of your dictionary values reference the same single list instance ([]) which you provide as a value to the fromkeys function.
You could use dictionary comprehension as seen in this answer.
dicCH = {key: [] for key in arrCH}

Resources