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}')
Related
Pretty much I'm trying to make a GPA calculator. I don't want anyone to just do the whole thing for me because I'm trying to figure out how to get 8 different values from the user in one line and add them together into one value. Most of the answers I've found online only talk about adding 2 values together so it's not of very much use to me...
I've tried using the ".split" function but really that's about it I'm new to python and dont have the background knowledge to really try much else.
No code, just need help with this problem
The expected result is to ask the user to put in 8 different grades between 0 and 100, then add them together into one value to later be divided.
If the GPAs come in in this format:
'3.3 3.6 2.7'
then you can read it in like this:
gpas = input('Please enter the GPAs in one line separated by spaces').split(' ')
and then you can loop through them (since split() returns a list), convert them to floats, and add them up, like so:
sum = 0
for gpa in gpas:
sum += float(gpa)
From what I read, I see you're getting the user's input as a string, from what you want to get the numbers the user entered and then operate with them, your problem being getting each separate number from the input. I think this other question on SO may help. Once you get each 'word' as an element of the array, you should convert each element to an int, getting the desired result.
Hope this helps!
I got the code working like this until i realized that the vertex index changes for geometry with over 100 vertices...
I assumed i could just split the string and everything would be dandy
import maya.cmds as mc
selPoints = mc.ls(sl = True) # list of names of selected vertices
objName = (str(selPoints[0]))[:-9]
print selPoints
print objName
Heres what it returned:
[u'pCylinder25.vtx[4]', u'pCylinder25.vtx[24]']
pCylinder
I'm trying to hack off the portion with '.vtx[integer]'
I may be going about this completely wrong, and there may be a dead simple way to do this.
Thanks
You can get the object from any valid selection string with the -o flag:
cmds.ls("pCube1.vtx[0]", o=True)
# pCubeShape1
Note that will be the shape, not the transform -- that's Maya being pedantic but it is correct. The transform would be
cmds.listRelatives(cmds.ls("pCube1.vtx[0]", o=True), p=True)
You may also find it helpful to split the components using partition:
object, _, component = "pCube1.vtx[0]".partition(".")
where the _ is python slang for 'ignore me'.
Wouldn't it be awesome if it were easy to get the object from Maya? From experience, I know it can be frustrating since MEL/maya.cmds doesn't use an object-oriented approach.
Anyhow, you should refer to the documentation often for more info on the variety of string methods you can use. Really comes in handy all the time!
To answer your question, you can use .split or .find, whichever you prefer.
print selPoints[0].split('.vtx')[0]
print selPoints[0][0:selPoints[0].find('.vtx')]
The split method returns a list of strings created by the delimiter string '.vtx'. Then, taking the first element from that list will always be the object name.
The find method returns the index of the substring '.vtx', so the second example simply uses slicing syntax to return the correct string.
just for stuff, using vanilla maya commands:
as mentioned with ls:
cm.ls("pCube1.vtx[0]", o=1) # will return shape pCubeShape1
with plugNode (opposite plugAttr):
cm.plugNode("pCube1.vtx[0]") # will return transform pCube1
I have written a python script where I have collected some values in a list. I need to pass on these values to an URL in a loop where in each time a different value is picked up.
i..e, I want to achieve this:
http://www.abc.com/xyz/pqr/symbol=something[i].
Here "something" is a list and I have verified that it contains the proper values. However when I pass the values to the URL, I am not getting the desired results. I have tried with URL encoding for something[i] but still it is not giving me proper results. Can someone help me?
EDIT: My example script at the moment is:
import json
script=["Linux","Windows"]
for i in xrange(len(script)):
site="abc.com/pqr/xyz/symbol=json.dumps(script[i])";
print site
I think the problem is your approach to formatting. You don't really need json if you have a list already and are just trying to modify a URL...
import json
script=["Linux","Windows"]
something = ["first","second"]
for i,j in zip(script,something):
site="http:abc.com/pqr/xyz/symbol={0}".format(j)
print i, site
This uses the .format() operator, which "sends" the values in parentheses into the string at the positions marked with {}. You could just add the strings together if it is always at the end. You could also use the older % operator instead. It does pretty much the same thing, but in this case it inserts the string j at the position marked by %s:
site="http:abc.com/pqr/xyz/symbol=%s" % (j)
Side note: I slightly prefer % because once you learn it, it can also be used in other programming languages, but .format() has more options and is the recommended way to do it since python 2.6.
Output:
Linux http:abc.com/pqr/xyz/symbol=first
Windows http:abc.com/pqr/xyz/symbol=second
You should be able to get close to what you want from this starting point, but if this is nothing like your desired output, then you need to clarify in your question...
I have been looking at Pandas: run length of NaN holes, and this code fragment from the comments in particular:
Series([len(list(g)) for k, g in groupby(a.isnull()) if k])
As a python newbie, I am very impressed by the conciseness but not sure how to read this. Is it short for something along the lines of
myList = []
for k, g in groupby(a.isnull()) :
if k:
myList.append(len(list(g)))
Series(myList)
In order to understand what is going on I was trying to play around with it but get an error:
list object is not callable
so not much luck there.
It would be lovely if someone could shed some light on this.
Thanks,
Anne
You've got the translation correct. However, the code you give cannot be run because a is a free variable.
My guess is that you are getting the error because you have assigned a list object to the name list. Don't do that, because list is a global name for the type of a list.
Also, in future please always provide a full stack trace, not just one part of it. Please also provide sufficient code that at least there are no free variables.
If that is all of your code, then you have only a few possibilities:
myList.append is really a list
len is really a list
list is really a list
isnull is really a list
groupby is really a list
Series is really a list
The error exists somewhere behind groupby.
I'm going to go ahead and strike out myList.append (because that is impossible unless you are using your own groupby function for some reason) and Series. Unless you are importing Series from somewhere strange, or you are re-assigning the variable, we know Series can't be a list. A similar argument can be made for a.isnull.
So that leaves us with two real possibilities. Either you have re-assigned something somewhere in your script to be a list where it shouldn't be, or the error is behind groupby.
I think you're using the wrong groupby itertools.groupby takes and array or list as an argument, groupby in pandas may evaluate the first argument as a function. I especially think this because isnull() returns an array-like object.
I have a CSV file with some words in, followed by a number and need a way to append the number; either adding 1 to it, or setting it back to 1.
Say for instance I have these words:
variant,1
sixty,2
game,3
library,1
If the user inputs the number sixty, how could I use that to add one onto the number, and how would I reset it back to 1?
I've been all over Google+Stackoverflow trying to find an answer, but I expect me not being able to find an answer was due more to my inexperience than anything.
Thanks.
This is a quick throw together using fileinput. Since I am unaware of the conditions for why you would decrease or reset your value, I added it in as an keyword arg you can pass at will. Such as
updateFileName(filename, "sixty", reset=True)
updateFileName(filename, "sixty", decrease=True)
updateFileName(filename, "sixty")
The results of each should be self-explanatory. Good luck! I wrapped it in a Try as I had no clue how your structure was, which will cause it to fail ultimately either way. If you have spaces you will need to .strip() the key and value.
import fileinput
def updateFileName(filename, input_value, decrease=False, reset=False):
try:
for line in fileinput.input(filename, inplace=True):
key, value = line.split(",")
if key == input_value:
if decrease:
sys.stdout.write("%s,%s"(key, int(value) - 1)
elif reset:
sys.stdout.write("%s,%s"(key, 1)
else:
sys.stdout.write("%s,%s"(key, int(value) + 1)
continue
sys.stdout.write(line)
finally:
fileinput.close()
Without knowing when you want to switch a number to 1 and when you want to add 1, I can't give a full answer, but I can set you on the right track.
First you want to import the csv file, so you can change it around.
The csv module is very helpful in this. Read about it here: http://docs.python.org/2/library/csv.html
You will likely want to read it into a dictionary structure, because this will link each word to it's corresponding number. Something like this make dictionary from csv file columns
Then you'll want to use raw_input (or input if you are using Python 3.0)
to get the word you are looking for and use that as the key to find and change the number you want to change. http://anh.cs.luc.edu/python/hands-on/handsonHtml/handson.html#x1-490001.12
or http://www.sthurlow.com/python/lesson06/
will show you how to get one part of a dictionary by giving it the other part and how to save info back into a dictionary.
Sorry it's not a direct answer. Maybe someone else will write one up, but it should get you started,
This is very probably not the best way to do it but you can load your csv file in an array object using numpy with the help of loadtxt().
The following code is going to give you a 2 dimension array with names in the first column and your numbers in the second one.
import numpy as np
a = np.loadtxt('YourFile',delimiter=',')
Perform your changes on the numbers the way you want and use the numpy savetxt() to save your file.
If your file is very heay, this solution is going to be a pain as loading a huge array takes a lot of memory. So consider it just as a workaround. The dictionary solution is actually better (I think).