Change Value in a list based on previous condition - python

I have a list of zeros and ones.
I am trying to replace the a value of 1 with a 0 if the previous value is also a 1 for a desired output as shown below.
list = [1,1,1,0,0,0,1,0,1,1,0]
new_list = [1,0,0,0,0,0,1,0,1,0,0]
I've tried using a for loop to no avail. Any suggestions?

How about this for loop:
list = [1,1,1,0,0,0,1,0,1,1,0]
new_list = []
ant=0
for i in list:
if ant ==0 and i==1:
new_list.append(1)
else:
new_list.append(0)
ant=i

question_list = [1,1,1,0,0,0,1,0,1,1,0]
new_list = [question_list[0]] # notice we put the first element here
for i in range(1, len(question_list) + 1):
# check if the current and previous element are 1
if question_list[i] == 1 and question_list[i - 1] == 1:
new_list.append(0)
else:
new_list.append(question_list[i])
The idea here is we iterate over the list, while checking the previous element.

Related

Compare each element of a list in existing order with elements of a second list in order as long as items in lists are equal

Compare each element of a list in existing order with elements of a second list in existing order as long as items in lists are equal. Stop if they're not equal and give me as result the index and name of the last match.
I thought it's straightforward with a while loop but it seems like this has to be approached with a for-loop.
My List one I want to compare:
nk_script_file_path
['P:', 'Projects', '2019_projects', '1910_My_Project', '01_Production_IN', '01_OFX', '01_Comp', '00_Nuke', 'relink_test_v001.nk']
My second list I want to compare it to:
node_filepath
['P:', 'Projects', '2019_projects', '1910_My_Project', '02_Production_OUT', '01_OFX', '01_Comp', '00_Nuke', '040_ALY', '040_ALY_040_HROTERRORBLADE', '040_ALY_040_HROTERRORBLADE_prev_Gamma22_apcs_mov', '040_ALY_040_HROTERRORBLADE_prev_v14_Gamma22_apcs.mov']
What I've tried
nk_script_file_path = r"P:/Projects/2019_projects/1910_My_Project/01_Production_IN/01_OFX/01_Comp/00_SO/relink_test_v001.nk".split("/")
node_filepath = r"P:/Projects/2019_projects/1910_My_Project/02_Production_OUT/01_OFX/01_Comp/00_S=/040_ALY/040_ALY_040_HROTERRORBLADE/040_ALY_040_HROTERRORBLADE_prev_Gamma22_apcs_mov/040_ALY_040_HROTERRORBLADE_prev_v14_Gamma22_apcs.mov".split("/")
# Compare file paths
path_object = 0
while nk_script_file_path in node_filepath:
path_object += 1
print path_object
print node_filepath[path_object]
Result I'm looking for:
"3"
or
"1910_My_Project"
You can use zip() with enumerate() to find first index where's difference. In this example if no difference is found, value of i is equal to -1:
lst1 = ['P:', 'Projects', '2019_projects', '1910_My_Project', '01_Production_IN', '01_OFX', '01_Comp', '00_Nuke', 'relink_test_v001.nk']
lst2 = ['P:', 'Projects', '2019_projects', '1910_My_Project', '02_Production_OUT', '01_OFX', '01_Comp', '00_Nuke', '040_ALY', '040_ALY_040_HROTERRORBLADE', '040_ALY_040_HROTERRORBLADE_prev_Gamma22_apcs_mov', '040_ALY_040_HROTERRORBLADE_prev_v14_Gamma22_apcs.mov']
for i, (a, b) in enumerate(zip(lst1, lst2)):
if a != b:
break
else:
i = -1
print('First difference is at index:', i)
Prints:
First difference is at index: 4
nk_script_file_path= r"P:/Projects/2019_projects/1910_My_Project/01_Production_IN/01_OFX/01_Comp/00_SO/relink_test_v001.nk".split("/")
node_filepath = r"P:/Projects/2019_projects/1910_My_Project/02_Production_OUT/01_OFX/01_Comp/00_S=/040_ALY/040_ALY_040_HROTERRORBLADE/040_ALY_040_HROTERRORBLADE_prev_Gamma22_apcs_mov/040_ALY_040_HROTERRORBLADE_prev_v14_Gamma22_apcs.mov".split("/")
j = 0
for i in nk_script_file_path:
if i != node_filepath[j] :
j = j-1
break
else:
j += 1
print(nk_script_file_path[j])
print(j)

How can I include or exclude a value in range?

I need to take a value, located in list.index()+1 position in order to use in a for range
li = [1,2,3,4,5,2,3,2,6]
indexar = [i for i, n in enumerate(li) if n == 3]
for i in li[0:indexar[0]]:
print(i)
I would like to get:
1
2
I've tried indexar[0]-1 but this doesn't work.
for i in li[0:indexar[0]-1]:
print(i)
How can I get this values without coding another for or some extra variables in order to add that 2?
If you want to exclude a number in the list, use continue in the for loop
li = [1,2,3,4,5,2,3,2,6]
for i in li:
if i == 3:
continue
print(i)
just do
li = [1,2,3,4,5,2,3,2,6]
end = 2
for i in range(0, end):
print(li[i])

Why can I print this list of lists, but only append all up to and not including the last element of each iteration?

I can print the following list of lists fine, but when I append to an empty list, it skips the last on each iteration or gives me an index out of range error when I add one more.
This works:
ordered_results = []
temp = []
A = len(results[1])-2
i = 1
while i < len(results):
x = 0
y = 1
while x < A:
temp = [results[i][0], results[0][x], results[i][y]]
print(temp)
x+=1
y+=1
temp = [results[i][0], results[0][x], results[i][y]]
print(temp)
i+=1
ordered_results
Note: len(results[0]) = 240 and len(results[1] = 241
If you replace "print" with ordered_results.append(temp) it skips:
results[i][0], results[0][239], results[i][240]
each iteration.
(Note the code was expanded as I am messing around trying to figure this out, it was more compact before).

python list within list initialization and printing

I am trying to append an element to a list within a list that has an incremented value each time:
def get_data(file):
matrix = [ ['one','two','three'] ] #list of lists
test_count = 0
line_count = 0 #keep track of which line we are on
for line in file:
if line.find('example') != -1: #test for example string
temp_a = re.findall(r"\'(.+?)\'",line)[0]
print matrix[test_count][0] #should print 'one'
matrix[test_count][0].insert(temp_a) #should insert temp_a instead of 'one'
test_count += 1 #go to next "new" list in the matrix
line_count += 1 #go to next line
What I want is the result of findall to go into temp_a and from there to insert it into index 0 of the first list within a list. Then the next time findall is true, I want to insert temp_a to index 0 of the second list.
For example if the first temp_a value is 9, I would like the first list in the matrix to be:
[ [9,y,z] ]
If on the second findall my temp_a is 4, I want the matrix to become:
[ [9,y,z], [4,y,z] ]
The above code is my best attempt so far.
I have 2 questions:
1) How can I initialize a 'list of lists' if the amount of lists isn't fixed?
2) The list ['one','two','three'] was to test with printing what is going on. If I try to print out matrix[test_count][0], I get an "index out of range" error, but the moment I change it to print out matrix[0][0] it prints 'one' correctly. Is there something with the scope that I'm missing here?
To answer your questions:
1) Like this: matrix = []
Simply put, this just creates an empty list that you can append anything you want into, including more lists. So matrix.append([1,2,3]) gives you a list like this: [[1,2,3]]
2) So you're index out of range error is coming from the fact that you're incrementing test_count to 1 but your matrix is remaining length of 1 (meaning it only has the 0 index) since you never append anything. In order to get the output that you want you're going to need to make a few changes:
def get_data(file):
example_list = ['one','two','three']
matrix = [] #list of lists
test_count = 0
line_count = 0 #keep track of which line we are on
for line in file:
if line.find('example') != -1: #test for example string
temp_a = re.findall(r"\'(.+?)\'",line)[0]
new_list = example_list[:]
new_list[0] = temp_a
matrix.append(new_list)
test_count += 1 #go to next "new" list in the matrix
line_count += 1 #go to next line
print matrix #[['boxes', 'two', 'three'], ['equilateral', 'two', 'three'], ['sphere', 'two', 'three']]
For 2), did you try to print out test_count? Since your test_count+=1 is in if statement, it shouldn't be out of range without printing "one".
For 1), you could do this before insert:
if test_count == len(matrix):
matrix.append([])
It adds a new empty list if test_count of out range of matrix.
EDIT:
"Out of range" caused by line temp_a = re.findall(r"\'(.+?)\'",line)[0] because it can't find anything. So it's an empty list, and [0] out of range.
def get_data(file):
matrix = [ ['one','two','three'] ] #list of lists
test_count = 0
line_count = 0 #keep track of which line we are on
for line in file:
if line.find('example') != -1: #test for example string
temp_a = re.findall(r"\'(.+?)\'",line)
if temp_a:
temp_a = temp_a[0]
else:
continue # do something if not found
print(matrix[test_count][0]) #should print 'one'
new_list = matrix[test_count][:]
new_list[0] = temp_a
matrix[test_count].append(new_list) #should insert temp_a instead of 'one'
test_count += 1 #go to next "new" list in the matrix
line_count += 1 #go to next line

Python - Finding next element in list matching a condition. Substitute previous entry

I have a list of elements to which I inputted some "identifiable" values that are not to go to my database. I want to find and substitute those values. Code looks like this (tried to be generic and illustrative, the date and time is predefined vars):
A = []
A.append(['Name1',date1,time1,0.00])
A.append(['Name1',date1,time2,0.00])
A.append(['Name2',date1,time1,price1])
A.append(['Name1',date1,time3,price2])
A.append(['Name1',date1,time4,price3])
A.append(['Name1',date2,time5,price4])
and so on. This 0.00 price should be changed by the next price where we have 'Name1' in position 0 and date1 in position 1, i.e.:
print(A[0])
print(A[1])
should yield
['Name1',date1,time1,price1]
['Name1',date1,time2,price1]
Appreciate your help.
Try this code for printing, pass the list and index for the same.
def print1(lists, index):
if lists[index][3] == 0:
try:
name=lists[index][0]
val = next(l[3] for l in lists[index:] if l[3]>0 and l[0]==name)
print lists[index][:-1] + [val]
except:
print "No value found with same name where price>0"
else:
print lists[index]
A=[]
A.append(['Name1','date1','time1',0.00])
A.append(['Name1','date1','time2',0.00])
A.append(['Name2','date1','time1',10])
A.append(['Name1','date1','time3',20])
A.append(['Name1','date1','time4',30])
A.append(['Name1','date2','time5',40])
print1(A,1)
you can return the values in place of printing them in case you need them to.
May be you need a method like this:
A = []
def insert_or_update_by_name_and_date(x):
if not isinstance(x, list) or len(x) < 2:
return
for element in A:
if len(element) < 2:
continue
if element[0] == x[0] and element[1] == x[1]:
element[2] = x[2]
element[3] = x[3]
return
A.append(x)
You can use two for loops:
for i in range(len(A)):
for j in range(i, len(A)):
if A[i][3] == 0.0 and A[j]]0] == 'Name1' and A[j][1] == date1:
A[i][3] = A[j][3]
Apart from that, you may find this discussion on when to use a Dictionary, List or Set useful.

Categories