How to modify the elements in a list within list
Date : March 29 2020, 07:55 AM
help you fix your problem As other people have explained, when you use the index function, it finds the first occurrence of the value you are search for. So the first time through you're loop (for the first row), it looks like b = 1
[1,2,3].find(1) # returns index 0
#Then you modify the first element of the list
b = 2
[2,2,3].find(2) #returns index 0 again!
for rowInd, x in enumerate(L):
for colInd, y in enumerate(x):
L[rowInd][colInd] = y + y
|
Create a list of lists. Modify elements in the list
Date : March 29 2020, 07:55 AM
will be helpful for those in need Requirement: def createMatDimXDim (dim):
lis=[[0] for i in range(dim)]
for i in range(dim):
lis[i][0]=i*10
for j in range(dim-1): # for the nested loop you need to use a new
# variable j
lis[i].append(int(lis[i][j])+1)
return lis
createMatDimXDim(4)
# [[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]]
dim = 4
[[i * 10 + j for j in range(dim)] for i in range(dim)]
# [[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]]
|
Python's list comprehension: Modify list elements if a certain value occurs
Date : March 29 2020, 07:55 AM
wish help you to fix your issue How can I do the following in Python's list comprehension? nums = [1,1,0,1,1]
[int(all(nums[:i+1])) for i in range(len(nums))]
[1, 1, 0, 0, 0]
if 0 in nums:
idx = nums.index(0)
new_list = [1] * idx + [0] * (len(nums) - idx)
new_list = nums[:idx] + [0] * (len(nums) - idx)
|
How can I modify elements in one list conditional on the elements in another list?
Date : March 29 2020, 07:55 AM
this will help You can store the names until you reach a none name then add it to the result. resA = []
resB = []
current = None
for a,b in zip(listA,listB):
if b == 'x':
if current:
resA.append(current)
resB.append('name')
current = None
resA.append(a)
resB.append(b)
else:
current= current + '_'+a if current else a
if current:
resA.append(current)
resB.append('name')
print(resA)
print(resB)
['my', 'name', 'is', 'dumbledore', ',', 'albus_dumbledore', '.', 'they', 'call', 'me', 'albus_percival_wulfric_brian_dumbledore', '.']
['x', 'x', 'x', 'name', 'x', 'name', 'x', 'x', 'x', 'x', 'name', 'x']
|
how to modify list of list by removing lists containing elements starting with the same pattern
Date : March 29 2020, 07:55 AM
help you fix your problem You can do this using a list comprehension. Assuming the pattern is always 3 characters, and you want to compare every element in each of the inner lists to every other element you can use the following new_lists_of_lists = [sublist for sublist in list_of_lists if not any(i[:3]==j[:3] and i!=j for i in sublist for j in sublist)]
|