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])
Related
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.
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)
From a list find out those values whose addition makes 9
aList=[81,26,27,19,108]
output, 81(because: 8+1),27(because: 2+7) and 108 (because:1+0+8)
I tried 2 approaches:
1st approach: I could not find a way to get the value, just get the sum
s=[81,18]
sum=0
for l in s:
while l:
l,dig=divmod(l,10)
sum=sum+dig
print(sum)
2nd approach: Nasty one indeed. Take individual values from list, convert to string to separate them and again convert to int.
s=[81] #9
sum=0
for item in s: #81
item=str(item) # 81 to string so I can get 8 and 1
for i in item:
while i:
i =int(i)
i,dig=divmod(i,10)
sum=sum+dig
print(sum,item)
Problem: In both cases it only works when I have single value in the list. When I have more than 1 value aList=[81,18] it gives me sum of those 2.
I would appreciate some hints/ideas on this one. Thanks in advance.
You could use the following list comprehension:
l = [81,26,27,19,108]
[i for i in l if sum(int(d) for d in str(i)) == 9]
# [81, 27, 108]
Which is equivalent to the following for loop:
res = []
for i in aList:
temp = []
for d in str(i):
temp.append(int(d))
if sum(temp) == 9:
res.append(i)
I have a list like
mylist = [75,75,76,77,78,79,154,155,154,156,260,262,263,550,551,551,552]
i need to remove numbers are close to each other by maxumim four number like:
num-4 <= x <= num +4
the list i need at the end should be like :
list = [75,154,260,550]
or
list = [76,156,263,551]
doesn't really matter which number to stay in the list , only one of those which are close.
i tried this which gave me :
for i in range(len(l)):
for j in range(len(l)):
if i==j or i==j+1 or i==j+2 or i == j+3:
pp= l.pop(j)
print(pp)
print(l)
IndexError: pop index out of range
and this one which doesn't work the way i need:
for q in li:
for w in li:
print(q,'////',w)
if q == w or q ==w+1 or q==w+2 or q==w+3:
rem = li.remove(w)
thanks
The below uses groupby to identify runs from the iterable that start with a value start and contain values that differ from start by no more than 4. We then collect all of those start values into a list.
from itertools import groupby
def runs(difference=4):
start = None
def inner(n):
nonlocal start
if start is None:
start = n
elif abs(start-n) > difference:
start = n
return start
return inner
print([next(g) for k, g in groupby(mylist, runs())])
# [75, 154, 260, 550]
This assumes that the input data is already sorted. If it's not, you'll have to sort it: groupby(sorted(mylist), runs()).
You can accomplish this using a set or list, you don't need a dict.
usedValues = set()
newList = []
for v in myList:
if v not in usedValues:
newList.append(v)
for lv in range(v - 4, v + 5):
usedValues.add(lv)
print(newList)
This method stores all values within 4 of every value you've seen so far. When you look at a new value from myList, you only need to check if you've seen something in it's ballpark before by checking usedValues.
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.