I'm making a conditional statement in openpyxl Python to check if a cell is empty. Here's my code:
newlist = []
looprow = 1
print ("Highest col",readex.get_highest_column())
getnewhighcolumn = readex.get_highest_column()
for i in range(0, lengthofdict):
prevsymbol = readex.cell(row = looprow,column=getnewhighcolumn).value
if prevsymbol == "None":
pass
else:
newstocks.append(prevsymbol)
looprow += 1
#print (prevsymbol)
print(newlist)
I tried if prevsymbol == "": and if prevsymbol == null: to no avail.
You compare prevsymbol with str "None", not None object. Try
if prevsymbol == None:
Also here
prevsymbol = readex.cell(row = looprow,column=getnewhighcolumn).value
you use looprow as row index. And you increment looprow only if cell.value is not empty. Here
newstocks.append(prevsymbol)
you use newstocks instead of newlist. Try this code
newlist = []
print ("Highest col",readex.get_highest_column())
getnewhighcolumn = readex.get_highest_column()
for i in range(0, lengthofdict):
prevsymbol = readex.cell(row = i+1,column=getnewhighcolumn).value
if prevsymbol is not None:
newlist.append(prevsymbol)
print(newlist)
Take the quotes away from the None.
if prevsymbol is None:
This is the python equivalent of checking if something is equal to null.
Related
car_file = open("car.txt", "r")
count = 0
for car_record in car_file:
car_record = car_record.strip('\n')
value = car_record.split(',')
print((count+1),'.', car_record)
count+=1
car_file.close()
car.txt
I want to only print the line that [7] is available
Since your availability is in the last column, you could use value[-1] to access it. I think you should have a look at if statements first. However, here is some code to help you out:
car_file = open("car.txt", "r")
count = 0
for car_record in car_file:
car_record = car_record.strip('\n')
value = car_record.split(',')
if value[-1] == "AVAILABLE":
print((count+1),'.', car_record)
count+=1
car_file.close()
Check if string is in value:
print(value) if 'AVAILABLE' in value else False
I was expecting this code to print "new string" between each row in my dataframe...
def isASCII(input_string):
print(input_string)
if isinstance(input_string, str):
orig_length = len(input_string)
print('new String!')
listThing = [letter for letter in input_string if ord(letter) < 127]
print(listThing)
new_length = len(listThing)
return (orig_length == new_length)
else:
return False
#isASCII('test') true
#isASCII('一些文字') false
#isASCII('sometext字') false
english_ga = dupe_free_ga.loc[isASCII(dupe_free_ga['App'].to_string())]
Instead 'new string!' appears once. Am I just not understanding how loc works here?
Let's try to split this line
english_ga = dupe_free_ga.loc[isASCII(dupe_free_ga['App'].to_string())]
to illustrate how Python evaluates it:
tmp = isASCII(dupe_free_ga['App'].to_string())
english_ga = dupe_free_ga.loc[tmp]
So, what would you expect dupe_free_ga.loc[True] or dupe_free_ga.loc[False] to return? Isn't that exactly what you get there?
I'm trying to iterate through a csv file, and am getting this error when calling the haversine function to calculate the distance between two locations. I'm confused because the variable seems to be assigned above?
def distance(dep, dest):
depfound = False
arrfound = False
for rowm in csv_reader:
for row in rowm.items():
if depfound == True and arrfound == True:
print ("BREAKING")
break
else:
if row[0] == (dep):
print (row[0])
depcoord = row[11]
print (depcoord)
depfound = True
if row[0] == (dest):
arrcoord = row[11]
print (arrcoord)
arrfound = True
print (haversine(depcoord, arrcoord))
distance("EGKK", "LFMN")
This is because in case your control doesnt come to "else", then the variable is undefined as the print will be executed in all cases.
Following should work
def distance(dep, dest):
depfound = False
arrfound = False
depcoord = None # or any other value as default eg - False
arrfound = None
for rowm in csv_reader:
for row in rowm.items():
if depfound == True and arrfound == True:
print ("BREAKING")
break
else:
if row[0] == (dep):
print (row[0])
depcoord = row[11]
print (depcoord)
depfound = True
if row[0] == (dest):
arrcoord = row[11]
print (arrcoord)
arrfound = True
print (haversine(depcoord, arrcoord))
distance("EGKK", "LFMN")
You call a print with an uninitialized variable. Initialize the variable depcoord = False.
Here is my code for 8 queen problem and why my output are all empty list ([])?
I have checked this statement print "result ok", result will get non-empty results.
class Solution(object):
def __init__(self, finalResult):
self.finalResult = finalResult
def Valid(self,result):
currentX = len(result) - 1
currentY = result[-1]
if currentX == 0:
return True
for i in range(0, len(result) - 1):
if result[i] == currentY:
return False
elif abs(i - currentX) == abs(result[i] - currentY):
return False
return True
def NQueens(self, result):
if result == []:
row = 0
else:
row = len(result)
for col in range(0, 8):
result.append(col)
if self.Valid(result) == True:
# print "check valid ok", row, col, result
if row == 7:
# print "result ok", result
self.finalResult.append(result)
else:
self.NQueens(result)
result.pop(-1)
return
if __name__ == "__main__":
finalResult = []
s = Solution(finalResult)
s.NQueens([])
print len(s.finalResult)
for i in s.finalResult:
print i
Output,
92
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
You should replace
self.finalResult.append(result)
with
self.finalResult.append(result[:])
This will create a copy of the "result". Your current code is creating several references to the same result which all get emptied by result.pop(-1)
You have only one list result that you manipulate. When you append, you append a 'reference' to that list and then you keep modifiying it. At the end it is empty so you print 92 times that empty list. You just need to create a copy of the current result before appending it.
I am trying to write a python script for Maya that will copy keyframes from one rig to another. I have found objects and matched them up. What I am trying to do now is copy the keys from the original objects if the original objects have keys to be copied. I was hoping to use the Keyframe command to check to see if the object has keys.
Example: if cmds.keyframe(oldObjPath attribute=oldAttr,sl=True, q=True, tc=True ) > 0:
This however always returned false. When I print out the attributes of oldObjPath I do get all the attributes printed out. Any idea what I am doing wrong here? Full code is below
Documentation on Keyframe Command:
http://download.autodesk.com/global/docs/maya2014/en_us/index.html?url=files/Python_Python_in_Maya.htm,topicNumber=d30e813275
#create a decunary of the object names and paths for faster searching
#[search_name:path]
originalObjectDic = {}
newObjectDic = {}
for obj in originalObjects:
#First remove the full path to give us somthing to search the new object with
subStrLoc = 0
index = 0
for char in obj:
if char == ':':
subStrLoc = index
index=index+1
searchName = obj[subStrLoc+1:]
originalObjectDic.update({searchName:obj})
#next look at all the names of the new object and see if they match up
for nObj in newObjects:
#correct the new objects name
subStrLoc=0
index=0
for char in nObj:
if index != 0:
if char == '_' and nObj[index-1] == 'r' and nObj[index-2] == 'u' and nObj[index-3] == 'F':
subStrLoc = index
index = index + 1
if subStrLoc == 0:
index = 0
for char in obj:
if char == ':':
subStrLoc = index
index=index+1
searchName = nObj[subStrLoc+1:]
newObjectDic.update({searchName:nObj})
#now that we have to dicunaries to check agaenst we will match up the two obj paths
# and copy the keys on all attributes on each node
for key in newObjectDic:
newObjPath = newObjectDic.get(key)
oldObjPath = originalObjectDic.get(key)
#if there is a match between the two dics
if newObjPath != None and oldObjPath != None:
#get a list of all the attributes
newObjAttributes = cmds.listAttr(newObjPath,v=True,r=True, w=True)
oldObjAttributes = cmds.listAttr(oldObjPath,v=True,r=True, w=True)
for x in range(len(newObjAttributes)-1):
newAttr = newObjAttributes[x]
oldAttr = oldObjAttributes[x]
if cmds.keyframe(oldObjPath attribute=oldAttr,sl=True, q=True, tc=True ) > 0:
print oldObjPath
print oldAttr
print 'Has Key'
print '----------------------------'
Got help from a freands. Had the wrong option on. sl which stands for selection should be false or not there at all so...
if cmds.keyframe(oldObjPath, attribute=oldAttr, sl=False, q=True, tc=True):