Change "example" with current selection based on setattr("example".outmesh) - python

I told myself to never ask common sense or novice questions if I can look it up on the web and to resort to asking people as the last resort. This will probably be a fundamental question but please do enlighten me!
My code :
obj = pm.ls (selection=True,sn=True,o=True) # get selection = obj
shapes = pm.listRelatives(obj) # get obj shapeNode name
cpmNode = pm.createNode('closestPointOnMesh') # create
closestPointOnMesh Node
pm.setAttr(shapes+".outMesh",cpmNode + ".inMesh") # setattr selection
shapeNode to cpmNode inMesh
Error :
# Can only concatenate list (not "str") to list
I don't understand how pm.setAttr(shapes+".outMesh",cpmNode + ".inMesh") is making into a list. Isn't it a command with strings now?
And by putting shapes into pm.setAttr(shapes+".outMesh",cpmNode + ".inMesh") is giving me errors where .outmesh is a string?
Is pm.setAttr(shapes+".outMesh",cpmNode + ".inMesh") a list then?
How should I make my current selection shapeNode to change pCubeShape1 if given example (below):
pm.setAttr("pCubeShape1.outMesh",cpmNode + ".inMesh")

As you suspected, cmds.listRelatives returns a list, not a string. That's because a transform can contain multiple shapes.
Also you cannot use setAttr to connect the shape's outMesh to the utility's inMesh. Instead you need to use connectAttr.
Try this:
import pymel.core as pm
obj = pm.ls (selection=True,sn=True,o=True)
shapes = pm.listRelatives(obj, shapes=True, ni=True, type="mesh") # Use flags to narrow down the proper shape.
cpmNode = pm.createNode('closestPointOnMesh')
pm.connectAttr(shapes[0]+".outMesh",cpmNode + ".inMesh") # Use the first item in the shapes list.

Related

How do I add a string to an element inside a list?

I'm learning lists and in order to get a better understanding I thought I'd apply some basic concepts I've learned so far.
What I'm attempting to do through my code is to add a new name to my list_of_Names and have it add a last name automatically. This is where I'm stuck.
My solution was using " Washington".join(newPerson) but that clearly doesn't work.
And please don't mind the efficiency of the code, I'm creating a new list just so I can apply the pop() command in a new scenario.
Also I've looked up similar issues, please don't tell me to use the map() command if it is somehow possible.
list_of_Names = ["Wallace Washington"]
def addNewMemeber(name):
newPerson = []
newPerson.append(name)
" Washington".join(newPerson)
list_of_Names.append(newPerson.pop())
addNewMemeber("William")
print(list_of_Names, end=", ")
1). I have rewritten your code again to get your desired result:-
list_of_Names = ["Wallace Washington"]
def addNewMemeber(name):
name = name + " Washington"
# If surname is fixed. If not then store surnames in a list and then perform logic by if-else.
list_of_Names.append(name)
addNewMemeber("William")
print(list_of_Names, end=", ")
2). Same Solution with join() method.
list_of_Names = ["Wallace Washington"]
def addNewMemeber(name):
l = []
l.append(name)
l.append("Washington")
name = " ".join(l)
# Join is used to convert list into string.
list_of_Names.append(name)
addNewMemeber("William")
print(list_of_Names, )
I hope this will help you.
You just need to add a string to the list list_of_names. There is no point in the newPerson list
def addNewMemeber(name):
list_of_Names.append(f'{name} Washington')
In order to use the pop command for the sake of it, theres 2 problems.
Your call to join doesn't save the result to a variable
Join doesn't make any sense.
So if you really want to add to the newPerson list, then don't use join whatsoever..
def addNewMemeber(name):
newPerson = [f'{name} Washington']
list_of_Names.append(newPerson.pop())
You can read about join function here.
I think the code you are looking for is as follows:
list_of_Names = ["Wallace Washington"]
def addNewMemeber(name):
name += ' Washington'
list_of_Names.append(name)
addNewMemeber("x")

work with image: imgcompare does not support list?

import imgcompare
...
for filename in os.listdir(myPath):
if filename.endswith(".png"):
listIm1.append(filename)
for filename2 in os.listdir(myPath2):
if filename2.endswith(".png"):
listIm2.append(filename2)
so i fill my two lists with images,now I would like to compare the images of the two lists one by one following the same index, for example:listIm1[0] with listImg2[0]listIm1[1] with listImg2[1]and so on... and that's the code:
for item in listIm1:
ifSame = imgcompare.is_equal(listIm1[item],listIm2[item],tolerance=2)
print ifSame
but get the error:
same = imgcompare.is_equal(listIm1[item], listIm2[item], tolerance=2)
TypeError: list indices must be integers, not str
it seems that imgcompare.is_equal() does not work with lists, is there some pythonic expedient to make it
works?
since
if filename2.endswith(".png"):
listIm2.append(filename2)
for item in listIm1:
# item = "someimagine.png"
ifSame = imgcompare.is_equal(listIm1[item],listIm2[item],tolerance=2)
#listIm1[someimagine.png] is what you are asking => retrun Type Error
I guess you are looking for something like this:
edit:
import os
for filename in os.listdir(myPath):
if filename2.endswith(".png"):
img_path = os.path.join(myPath,filename2)
listIm2.append(img_path)
listIm1 = []
listIm2 = []
for i in range(len(listIm1)):
ifSame = imgcompare.is_equal(listIm1[i],listIm2[i],tolerance=2)
print ifSame
and it's better if len(listIm1) == len(listIm2)
The problem here is that you are trying to get the index of listIm1 by using item. What you want to do is use a range(), like:
for i in range(len(listIm1)):
ifSame = imgcompare.is_equal(listIm1[i],listIm2[i],tolerance=2)
As #Matt pointed out, this will only work if you know the lists are the same length beforehand, otherwise it will throw an index error.
You are using a for each loop, which grabs each element in your provided list listIm1 and stores it in a temp variable item, you then pass item (which is a string) as an index both of your lists. Indices of a list must be an integer, and that is the error you are getting.
for dir1_file in listIm1:
for dir2_file in listIm2:
ifSame = imgcompare.is_equal(dir1_file,dir2_file,tolerance=2)
print ifSame
This code uses two for each loops, it looks at each element in both of the lists and uses them as the arguments for your method.

issue with adding two-dimensional array to string python

please help me.
I have two-dimensional array example :
self.history = [['23295', u'0.0500', u'0.0700', u'0.0600', u'0.0600'],['23295', u'0.0500', u'0.0700', u'0.0600', u'0.0600']]
i try parsing him and get string but have syntax error, please advice.
for i in range(int(cac)):
returning = returning + "\""+str(date_arr[i])+","+ str(self.history[0 for x in range(len(self.history))][i])+"+"
in output i need have somethings like :
"somedate,'23295','23295'" + "somedate,u'0.0500',u'0.0500'" + "somedate,u'0.0700',u'0.0700'"...
You have to use two for loops:
for x in range(len(self.history)):
for i in range(int(cac)):
returning = returning + "\""+str(date_arr[i])+","+ str(self.history[x][i])+"+"
Note that your code [x for x in range(len(self.history))] generates a list whereas you need an integer to index your list

accessing values of a dictionary with duplicate keys

I have a dictionary that looks like this:
reply = {icon:[{name:whatever,url:logo1.png},{name:whatever,url:logo2.png}]}
how do i access logo1.png ?
I tried :
print reply[icon][url]
and it gives me a error:
list indices must be integers, not str
EDIT:
Bear in mind sometimes my dictionary changes to this :
reply = {icon:{name:whatever,url:logo1.png}}
I need a general solution which will work for both kinds of dictionaries
EDIT2:
My solution was like this :
try:
icon = reply['icon']['url']
print icon
except Exception:
icon = reply['icon'][0]['url']
print ipshit,icon
This works but looks horrible. I was wondering if there was an easier way than this
Have you tried this?
reply[icon][0][url]
If you know for sure all the different kinds of responses that you will get, you'll have to write a parser where you're explicitly checking if the values are lists or dicts.
You could try this if it is only the two possibilities that you've described:
def get_icon_url(reply):
return reply['icon'][0]['url']\
if type(reply['icon']) is list else reply['icon']['url']
so in this case, icon is the key to a list, that has two dictionaries with two key / value pairs in each. Also, it looks like you might want want your keys to be strings (icon = 'icon', name='name').. but perhaps they are variables in which case disregard, i'm going to use strings below because it seems the most correct
so:
reply['icon'] # is equal to a list: []
reply['icon'][0] # is equal to a dictionary: {}
reply['icon'][0]['name'] # is equal to 'whatever'
reply['icon'][0]['url'] # is equal to 'logo1.png'
reply['icon'][1] # is equal to the second dictionary: {}
reply['icon'][1]['name'] # is equal to 'whatever'
reply['icon'][1]['url'] # is equal to 'logo2.png'
you can access elements of those inner dictionaries by either knowing how many items are in the list, and reference theme explicitly as done above, or you can iterating through them:
for picture_dict in reply['icon']:
name = picture_dict['name'] # is equal to 'whatever' on both iterations
url = picture_dict['url'] #is 'logo1.png' on first iteration, 'logo2.png' on second.
Cheers!
Not so different, but maybe it looks better (KeyError gives finer control):
icon_data = reply['icon']
try:
icon = icon_data['url']
print icon
except KeyError:
icon = icon_data[0]['url']
print ipshit,icon
or:
icon_data = reply['icon']
if isinstance(icon_data, list):
icon_data = icon_data[0]
icon = icon_data['url']

use slice in for loop to build a list

I would like to build up a list using a for loop and am trying to use a slice notation. My desired output would be a list with the structure:
known_result[i] = (record.query_id, (align.title, align.title,align.title....))
However I am having trouble getting the slice operator to work:
knowns = "output.xml"
i=0
for record in NCBIXML.parse(open(knowns)):
known_results[i] = record.query_id
known_results[i][1] = (align.title for align in record.alignment)
i+=1
which results in:
list assignment index out of range.
I am iterating through a series of sequences using BioPython's NCBIXML module but the problem is adding to the list. Does anyone have an idea on how to build up the desired list either by changing the use of the slice or through another method?
thanks zach cp
(crossposted at [Biostar])1
You cannot assign a value to a list at an index that doesn't exist. The way to add an element (at the end of the list, which is the common use case) is to use the .append method of the list.
In your case, the lines
known_results[i] = record.query_id
known_results[i][1] = (align.title for align in record.alignment)
Should probably be changed to
element=(record.query_id, tuple(align.title for align in record.alignment))
known_results.append(element)
Warning: The code above is untested, so might contain bugs. But the idea behind it should work.
Use:
for record in NCBIXML.parse(open(knowns)):
known_results[i] = (record.query_id, None)
known_results[i][1] = (align.title for align in record.alignment)
i+=1
If i get you right you want to assign every record.query_id one or more matching align.title. So i guess your query_ids are unique and those unique ids are related to some titles. If so, i would suggest a dictionary instead of a list.
A dictionary consists of a key (e.g. record.quer_id) and value(s) (e.g. a list of align.title)
catalog = {}
for record in NCBIXML.parse(open(knowns)):
catalog[record.query_id] = [align.title for align in record.alignment]
To access this catalog you could either iterate through:
for query_id in catalog:
print catalog[query_id] # returns the title-list for the actual key
or you could access them directly if you know what your looking for.
query_id = XYZ_Whatever
print catalog[query_id]

Categories

Resources