I have a several lists that I am trying to activate or use that are named as follows:
public_forum_jr_soc = []
parliamentary_jr_soc = []
european_jr_soc = []
etc...
I have a bunch of radiobuttons that has variables to recreate these lists names, and it outputs something like this.
print(self.select_league.get()+self.select_age.get()+self.select_grade.get())
append_name = self.select_league.get()+self.select_age.get()+self.select_grade.get()
>>>
european_jr_soc
I try to proceed to use this list in as an argument for a function.
output_data(append_name)
def master_groper2(outof48):
for i in outof48:
if i[15] in ['ENGLISH','english','']:
i[15] = 'English'
elif i[15] in ['Mandarin','CHINESE',]:
i[15] = 'Chinese'
However, I get a IndexError: string index out of range as python reads it as european_jr_soc, instead of the actual list, despite sharing the same name, how could I have python have it read it as the variable list?
Related
I try to create an object by passing the variables, but it seems not work.
I put a simple example below to show what I want. Please help me to deal with this issue.
Successfully
temp = catalog.TEST
temp = catalog.PROD
Not works, it pass string "i" instead of the list element as attributes
lists = ['TEST,'PROD']
for i in lists:
temp = catalog.i
Complete code
I'm using dremio-client this package (https://dremio-client.readthedocs.io/en/latest/readme.html)
import dremio_client as dc
mydremio = dc.init(os.getcwd() + '/.config')
catalog = mydremio.data
# TEST and PROD are the folders that exist in my dremio server
a = catalog.TEST
b = catalog.PROD
# Cannot pass the list element to object "catalog"
list = ["TEST","PROD"]
for i in list
temp = catalog.i
Thanks Pavel for the solution, but I have a one more complicated question.
list = ["TEST","TEST.DEMO"]
# what's work - directly declare
test = catalog.TEST.DEMO
# works for "TEST" not works for TEST.DEMO
for i in list:
temp = getattr(catalog, i)
When you do temp = catalog.i, you actually trying to set an attribute i of the catalog, not value under variable i.
You can try using getattr instead:
import dremio_client as dc
mydremio = dc.init(os.getcwd() + '/.config')
catalog = mydremio.data
# TEST and PROD are the folders that exist in my dremio server
a = catalog.TEST
For the second case you can try to do something like this:
for i in list:
fields = i.split('.')
temp = catalog
for field in fields:
temp = getattr(temp, field)
What I do here is split i by . symbol to create a list of fields that I need to access.
So "TEST.DEMO".split('.') will become ["TEST", "DEMO"]
Not sure if it will work, but I just wanted to show the main idea.
For some reason PyCharm is telling me that 3 of my 5 list are not used in my function but they in fact are being used in the function and the code completes with the expected results.
This is odd behavior. Is this a bug?
I have seen some issues for f-strings reporting false positives but I do not think this is the same issue here.
def filter_for_vzb_vzt(self, query_results):
vzb_list = []
vzt_list = []
vzt_analyst_tkr = []
vzb_analyst_tkr = []
vzb_lpc_analyst_tkr = []
with open('./Files/{}.json'.format('VZT_ACNA_LIST'), 'r') as df:
vzt_analyst_tkr = json.load(df)
with open('./Files/{}.json'.format('VZB_TAX_ACNA_LIST'), 'r') as df:
vzb_analyst_tkr = json.load(df)
with open('./Files/{}.json'.format('VZB_LPC_ACNA_LIST'), 'r') as df:
vzb_lpc_analyst_tkr = json.load(df)
self.process_vzb_mass(vzb_list, vzb_analyst_tkr, vzb_lpc_analyst_tkr)
self.process_vzt_mass(vzt_list, vzt_analyst_tkr)
self.active_time = False
You are indeed not using those values. Read carefully the message:
local variable <...> value is not used
PyCharm is being very specific - you are assigning these three variables a new list with
<...> = json...
The original empty lists that these variables pointed to are then discarded.
These assignments are not conditional, so you will never use those empty lists - PyCharm is warning you you are not using the empty lists, rather than the variables themselves. You should probably just delete those lines - common practice is to first define variables with values that will actually be used.
This is probably a very basic question but I haven't been able to figure this out.
I'm currently using the following to append values to an empty list
shoes = {'groups':['running','walking']}
df_shoes_group_names = pd.DataFrame(shoes)
shoes_group_name=[]
for type in df_shoes_group_names['groups']:
shoes_group_name.append(type)
shoes_group_name
['running', 'walking']
I'm trying to accomplish the same using a for loop, however, when I execute the loop the list comes back as blank
shoes_group_name=[]
def list_builder(dataframe_name):
if 'shoes' in dataframe_name:
for type in df_shoes_group_names['groups']:
shoes_group_name.append(type)
list_builder(df_shoes_group_names)
shoes_group_name
[]
Reason for the function is that eventually I'll have multiple DF's with different product's so i'd like to just have if statements within the function to handle the creation of each list
so for example future examples could look like this:
df_shoes_group_names
df_boots_group_names
df_sandals_group_names
shoes_group_name=[]
boots_group_name=[]
sandals_group_name=[]
def list_builder(dataframe_name):
if 'shoes' in dataframe_name:
for type in df_shoes_group_names['groups']:
shoes_group_name.append(type)
elif 'boots' in dataframe_name:
for type in df_boots_group_names['groups']:
boots_group_name.append(type)
elif 'sandals' in dataframe_name:
for type in df_sandals_group_names['groups']:
sandals_group_name.append(type)
list_builder(df_shoes_group_names)
list_builder(df_boots_group_names)
list_builder(df_sandals_group_names)
Not sure if I'm approaching this the right way so any advice would be appreciated.
Best,
You should never call or search a variable name as if it were a string.
Instead, use a dictionary to store a variable number of variables.
Bad practice
# dataframes
df_shoes_group_names = pd.DataFrame(...)
df_boots_group_names = pd.DataFrame(...)
df_sandals_group_names = pd.DataFrame(...)
def foo(x):
if shoes in df_shoes_group_names: # <-- THIS WILL NOT WORK
# do something with x
Good practice
# dataframes
df_shoes_group_names = pd.DataFrame(...)
df_boots_group_names = pd.DataFrame(...)
df_sandals_group_names = pd.DataFrame(...)
dfs = {'shoes': df_shoes_group_names,
'boots': df_boots_group_names,
'sandals': df_sandals_group_names}
def foo(key):
if 'shoes' in key: # <-- THIS WILL WORK
# do something with dfs[key]
So im running into an issue trying to get my dictionary to change within a function without returning anything here is my code:
def load_twitter_dicts_from_file(filename, emoticons_to_ids, ids_to_emoticons):
in_file = open(filename, 'r')
emoticons_to_ids = {}
ids_to_emoticons = {}
for line in in_file:
data = line.split()
if len(data) > 0:
emoticon = data[0].strip('"')
id = data[2].strip('"')
if emoticon not in emoticons_to_ids:
emoticons_to_ids[emoticon] = []
if id not in ids_to_emoticons:
ids_to_emoticons[id] = []
emoticons_to_ids[emoticon].append(id)
ids_to_emoticons[id].append(emoticon)
basically what im trying to do is to pass in two dictionaries and fill them with information from the file which works out fine but after i call it in the main and try to print the two dictionaries it says they are empty. Any ideas?
def load_twitter_dicts_from_file(filename, emoticons_to_ids, ids_to_emoticons):
…
emoticons_to_ids = {}
ids_to_emoticons ={}
These two lines replace whatever you pass to the function. So if you passed two dictionaries to the function, those dictionaries are never touched. Instead, you create two new dictionaries which are never passed to the outside.
If you want to mutate the dictionaries you pass to the function, then remove those two lines and create the dictionaries first.
Alternatively, you could also return those two dictionaries from the function at the end:
return emoticons_to_ids, ids_to_emoticons
I am trying to set up a function that will query an item for its sub components if those exists and return those else return the item itself.
Imagine an object that can contain more objects within it. To access those objects i would do object.GetSubComponentIds() now if that object contains sub objects it would return a list of those sub objects or EmptyList if there are none. In case that there are sub objects contained within it I want to keep going and then for each subobject i want to check if there are any subobjects contained within them. So for every SubObject.GetSubComponentIds() now if those do not contain anything then i would love to return them while maintaining nested structure of objects that they came from.
object1(contains 3 sub objects)
object2(contains 3 sub object and each sub object contains one more sub object)
object3(does not contain sub objects)
inputlist = [object1, object2]
outputlist = [[obj1sub1, obj1sub2, obj1sub3],[[obj2sub1sub1],[obj2sub2sub1],[obj2sub3sub1]],[obj3]]
I am interested in maintaining that nested list structure that will allow me to always trace back the origin of the sub object. Again, a method to get a sub object list is object.GetSubComponentIds() and it will either return a list or Empty List.
Can anyone help me set up an iterative function to retrieve them. Keep in mind that I do not know whether there are any sub objects contained within an object or haw many levels deep are they. It's basically that if it returns a list i need to check every item on that list for more sub objects.
Thank you in advance
Here's my humble first try:
#unwrap all elements to use with API
elements = []
for i in IN[0]:
elements.append(UnwrapElement(i))
#create element set from python list
elementSet = Autodesk.Revit.DB.ElementSet()
for i in elements:
elementSet.Insert(i)
#convert element set to List[Element]
setForCheck = List[Autodesk.Revit.DB.Element]()
elemIter = elementSet.ForwardIterator()
elemIter.Reset()
while elemIter.MoveNext():
curElem = elemIter.Current
setForCheck.Add(curElem)
#iterate throuh all elements to extract nested elements
setLoop = List[Autodesk.Revit.DB.Element]()
elemSet = List[Autodesk.Revit.DB.Element]()
itemOut = []
counter = 0
while setForCheck.Count >= 1:
setLoop.Clear()
for i in setForCheck:
itemOut.append(i)
if i.GetSubComponentIds().Count >= 1:
elem = Autodesk.Revit.DB.ElementSet()
for j in i.GetSubComponentIds():
elem.Insert(doc.GetElement(j))
elemIterA = elem.ForwardIterator()
elemIterA.Reset()
while elemIterA.MoveNext():
curElemA = elemIterA.Current
setLoop.Add(curElemA)
setForCheck.Clear()
elemIterB = setLoop.GetEnumerator()
elemIterB.Reset()
while elemIterB.MoveNext():
curElemB = elemIterB.Current
setForCheck.Add(curElemB)
counter += 1
if counter > 1000:
break
#Assign your output to the OUT variable
OUT = itemOut
You're using some specific libraries, like Autodesk, that I'm not familiar with. Let me answer your question in terms of an abstract example.
Suppose we're dealing with Thing objects, where Thing is defined as:
class Thing(object):
def __init__(self, name):
self.name = name
self.inside = []
We can make Things and put other things inside of them. The example you give in your post can be written:
ob1 = Thing("ob1")
ob1.inside.extend([Thing("ob1sub1"), Thing("ob1sub2"), Thing("ob1sub3")])
ob2 = Thing("ob2")
for i in xrange(1,4):
name = "ob2sub{}".format(i)
thing = Thing(name)
thing.inside.append(Thing(name + "sub1"))
ob2.inside.append(thing)
ob3 = Thing("ob3")
things = [ob1, ob2, ob3]
This makes a sort of tree. Now we'd like to return a nested list of all of the leaf nodes in the tree:
def search_things(things):
names = []
for thing in things:
if not thing.inside:
names.append(thing)
else:
names.append(search_things(thing.inside))
return names
A test:
>>> search_things(things)
[['ob1sub1', 'ob1sub2', 'ob1sub3'],
[['ob2sub1sub1'], ['ob2sub2sub1'], ['ob2sub3sub1']],
'ob3']
I'll let you transform this to your specific problem, but this is the general idea. Note that the algorithm is recursive, not iterative. You said you wanted an iterative algorithm -- and the above can be written iteratively -- but this gives you the idea.