in Python how does one call the current position of a interation in a "for x, y, z in list():"?
I have a list with numerous subsists consisting of three variables, but I don't quite know how to call the current position of the loop - ie. Call the value of X in the current iteration of the loop.
I am really new to coding and python so any help would be appreciated greatly - I read something about enumerate but that just confused me and I didn't know whether it would help or how to reference it or use it
currently my loop looks like:
for step_num, direction, changes in movements:
with movements being a list consisting of multiple sub lists with three variables each (one numeric and two alphanumeric). my goal is to be able to reference the current variable of the current sublist being iterated through - I'd read something about enumerate potentially being able to help with finding the current value of a sub list variable, however I don't know how to use it as such, if indeed it can be used like that, especially since the output is being used in a turtle window to draw different objects.
As it stands I'm not sure how to make it happen, so the functions making drawings don't know how to draw the current value in the loop
you can use enumerate(list) like so:
for index, y in enumerate(list):
print(index) # position of loop
print(y) # item in list
I'm making some assumptions here, but are you looking for something like this?
# iterate through each sublist in `movements`
# and also get its index
for ix, movement in enumerate(movements):
for step_num, direction, changes in movement: # extract the values from each sublist
... # do stuff with the index and corresponding values
P.S.: If you are new to SO, please take sometime to learn how to produce a minimal reproducible example. It will only increase your chances of getting a quick and useful response.
Related
I have a curve_hex generator, it uses two coordinates, I'm looking for only one coordinate. The script searches for one coordinate value easily, but if I specify several coordinates for the search, then it does not find anything.
wanted='58611774815559422402170859520215717661755632997646071327165159211728464937238'
curve_hex='(58611774815559422402170859520215717661755632997646071327165159211728464937238, 108722706890170119196943746054760504186165603293283329661416022207913727808252)'
if str(curve_hex).find(wanted)!=-1:
print (curve_hex[str(curve_hex).find(wanted):str(curve_hex).find(wanted)+len(wanted)])
else:
print ('not')
One value is found normally. But if I add several values, the script writes an error
wanted='58611774815559422402170859520215717661755632997646071327165159211728464937238', '108722706890170119196943746054760504186165603293283329661416022207913727808252'
curve_hex='(58611774815559422402170859520215717661755632997646071327165159211728464937238, 108722706890170119196943746054760504186165603293283329661416022207913727808252)'
if str(curve_hex).find(wanted)!=-1:
print (curve_hex[str(curve_hex).find(wanted):str(curve_hex).find(wanted)+len(wanted)])
else:
print ('not')
Tell me how to do it right. What am I doing wrong. I have just started learning python.
Very exciting that you are learning python, I would also suggest that you might want to spend some time in the stackoverflow section explaining how to ask a question because I am not 100% sure what you are trying to achieve with your code.
From my understanding, if you are happy with your if else conditions, and your only problem is that you can’t add multiple values to wanted. I would convert wanted to a list that includes all your wanted values, and loop over those.
Something like this:
wanted = ['586..{copy the whole value here}', '108...{copy the value here}']
curve_hex='(58611774815559422402170859520215717661755632997646071327165159211728464937238, 108722706890170119196943746054760504186165603293283329661416022207913727808252)'
for value in wanted:
if str(curve_hex).find(value)!=-1:
print (curve_hex[str(curve_hex).find(value):str(curve_hex).find(value)+len(value)])
else:
print ('not')
Edit: formatting and typos
You are misleadiong some basic concepts:
Difinitions like this result in diferent types
wanted='58611774815559422402170859520215717661755632997646071327165159211728464937238'
type(wanted) # string
wanted='58611774815559422402170859520215717661755632997646071327165159211728464937238', '108722706890170119196943746054760504186165603293283329661416022207913727808252'
type(wanted) # tuple
curve_hex='(58611774815559422402170859520215717661755632997646071327165159211728464937238, 108722706890170119196943746054760504186165603293283329661416022207913727808252)'
type(wanted) # string
So you should choose a type first. Tuple is the best case.
wanted=('58611774815559422402170859520215717661755632997646071327165159211728464937238', '108722706890170119196943746054760504186165603293283329661416022207913727808252')
curve_hex=('58611774815559422402170859520215717661755632997646071327165159211728464937238', '108722706890170119196943746054760504186165603293283329661416022207913727808252')
for i in wanted:
for x,j in enumerate(curve_hex):
if i in j:
print(f'{i} in {curve_hex} at position {x}')
This question already has answers here:
Scope of python variable in for loop
(10 answers)
Closed 6 years ago.
# Padraic Cunningham Let me know if you want me to delete the
question.
I am new to python. I want to skip some iterator values based on some condition. This is easy in C but in python I am having a hard time.
So please help me in understanding why the code here loops 100 times instead of 10.
for i in range(100):
print i
i = i +10
edit: I understand there is option to change step size of for loop. But I am interested in dynamically changing the iterator variable, like we can do in C. Okay, i get it, for loop is different in python than in C. Easy way to do is use the while loop, I did that in my code and it worked. Thank you community!
The for loop is walking through the iterable range(100).
Modifying the current value does not affect what appears next in the iterable (and indeed, you could have any iterable; the next value might not be a number!).
Option 1 use a while loop:
i = 0
while i < 100:
i += 4
Option 2, use the built in step size argument of range:
for i in range(0,100,10):
pass
This example may make it clearer why your method doesn't make much sense:
for i in [1,2,3,4,5,'cat','fish']:
i = i + i
print i
This is entirely valid python code (string addition is defined); modifying the iterable would require something unintuitive.
See here for more information on how iterables work, and how to modify them dynamically
To do this use a while loop. Changing the iterator in a for loop will not change the amount if times it iterates Instead you can do
i=0
while i < 100:
print i
i = i +10
If you want to update an iterator, you can do something like that :
iterator= iter(range(100))
for i in iterator:
print (i)
for k in range(9): next(iterator)
But no practical interest !
If you try this code it should work.
for i in range(100)[::10]:
print i
The [::10] works like string slicing. [first position to start at: position to stop at:number to steps to make in each loop]
I didn't use the first two values so these are set to the default of first position and last position. I just told it to make steps of 10.
I have a dictionary created from a json file. This dictionary has a nested structure and every few weeks additional parameters are added.
I use a script to generate additional copies of the existing parameters when I want multiple "legs" added. So I first add the additional legs. So say I start with 1 leg as my template and I want 10 legs, I will just clone that leg 9 more times and add it to the list.
Then I loop through each of the parameters (called attributes) and have to clone certain elements for each leg that was added so that it has a 1:1 match. I don't care about the content so cloning the first leg value is fine.
So I do the following:
while len(data['attributes']['groupA']['params']['weights']) < legCount:
data['attributes']['groupA']['params']['weights'].append(data['attributes']['groupA']['params']['weights'][0])
while len(data['attributes']['groupB']['paramsGroup']['factors']) < legCount:
data['attributes']['groupB']['paramsGroup']['factors'].append(data['attributes']['groupB']['paramsGroup']['factors'][0])
while len(data['attributes']['groupC']['items']['delta']) < legCount:
data['attributes']['groupC']['items']['delta'].append(data['attributes']['groupC']['items']['delta'][0])
What I'd like to do is make these attributes all strings and just loop through them dynamically so that when I need to add additional ones, I can just paste one string into my list and it works without having another while loop.
So I converted it to this:
attribs = [
"data['attributes']['groupA']['params']['weights']",
"data['attributes']['groupB']['paramsGroup']['factors']",
"data['attributes']['groupC']['items']['delta']",
"data['attributes']['groupD']['xxxx']['yyyy']"
]
for attrib in attribs:
while len(eval(attrib)) < legCount:
eval(attrib).append(eval(attrib)[0])
In this case eval is safe because there is no user input, just a defined list of entries. Tho I wouldn't mind finding an alternative to eval either.
It works up until the last line. I don't think the .append is working on the eval() result. It's not throwing an error.. just not appending to the element.
Any ideas on the best way to handle this?
Not 100% sure this will fix it, but I do notice one thing.
In your above code in your while condition you are accessing:
data['attributes']['groupA']['params']['weights']
then you are appending to
data['attributes']['groupA']['params']['legs']
In your below code it looks like you are appending to 'weights' on the first iteration. However, this doesn't explain the other attributes you are evaluating... just one red flag I noticed.
Actually my code was working. I was just checking the wrong variable. Thanks Me! :)
I am trying to learn about while and for loops. This function prints out the highest number in a list. But, I'm not entirely sure how it works. Can anyone break down how it works for me. Maybe step by step and/or with a flowchart. I'm struggling and want to learn.
def highest_number(list_tested):
x=list_tested[0]
for number in list_tested:
if x<number:
x=number
print(x)
highest_number([1,5,3,2,3,4,5,8,5,21,2,8,9,3])
One of the most helpful things for understanding new code is going through it step by step:
PythonTutor has a visualizer: Paste in your code and hit visualize execution.
What this is going form the first to the last number and saying:
Is this new number bigger than the one I have? If so, keep the new number, if not keep the old number.
At the end, x will be the largest number.
See my comments for step by step explanation of each line
def highest_number(list_tested): # function defined to take a list
x=list_tested[0] # x is assigned the value of first element of list
for number in list_tested: # iterate over all the elements of input list
if x<number: # if value in 'x' is smaller than the current number
x=number # then store the value of current element in 'x'
print(x) # after iteration complete, print the value of 'x'
highest_number([1,5,3,2,3,4,5,8,5,21,2,8,9,3]) # just call to the function defined above
So basically, the function finds the largest number in the list by value.
It starts by setting the large number (x) as the first element of list, and then keeps comparing it to other elements of the list, until it finds an element which is greater than the largest number found till now (which is stored in x). So at the end, the largest value is stored in x.
Looks like you are new to the programming world. Maybe you should start with some basic concepts, for/while loops are some among which, that would be helpful for you before jumping into something like this.
Here is one of the explanations you may easily find on the Internet http://www.teamten.com/lawrence/programming/intro/intro8.html
I'm trying to solve this: CodeEval.
The problem requires me to go through a list of possible candidates of points in a XY-coordinates. Then if they fulfill the requirements I add them to a "confirmed" list and then add the surrounding points to a "tosearch" list. However this does not behave at all the way I expect it to behave.
Example code:
Starting point
tosearch=[[0,0]]
for point in tosearch:
if conditions filled:
confirmed.append(point)
#Basically Im trying to add (x,y-1) etc. to the tosearct list
tosearch.append([point[0],point[1]-1]) #1
tosearch.append([point[0]+1,point[1]]) #2
tosearch.append([point[0]-1,point[1]-1])#3
tosearch.append([point[0],point[1]+1]) #4
tosearch.remove(point)
else:
tosearch.remove(point)
This seems to result in always ignoring half of the appends. So in this case #1 and #3 are being ignored. If I left only 1&2 then only 2 would execute. I dont get it...
Maybe the problem is else where so here is the whole code:
Pastebin
You're modifying the collection while iterating over it.
2 options:
copy the list, iterate the copy, and alter the original.
keep track of what changes need to be made, and make them all at after iterating.
The problem is you are modifying tosearch in the body of the loop that iterates tosearch. Since tosearch is changing, it can't be iterated reliably.
You probably don't need to iterate at all. Just use a while loop:
searched = set() # if you need to keep track of searched items
tosearch = [(0,0)] #use tuples so you can put them in a set
confirmed = []
while tosearch:
point = tosearch.pop()
searched.add(point) # if you need to keep track
if CONDITIONS_MET:
confirmed.append(point)
# tosearch.append() ....