I am new in python,
I want work with structured lists:
class X_ItemSet: # Structure of an Item
Item = []
ItemTID = []
oneItem = X_ItemSet #one instance of X_ItemSet
ListTID = [X_ItemSet] #Liste of X_ItemSet
oneItem.Item.append(1)
oneItem.ItemTID.append("a")
ListTID.append(oneItem)
del oneItem[:]
my problem is when deleting oneItem also ListTID will be empty
what should i do to keep values in ListTID when deleting oneItem?
Related
I have the following code
entries = soup.find_all("entry")
master_list_xml = []
for entry in entries:
accession_num = entry.find("accession-number").text
print(accession_num)
Output is:
0001564590-18-019062
0001564590-17-014900
0001193125-16-662209
0001193125-15-272806
Now, I want to make a list containing every accession_num.
Question: What is the most efficient way to do it?
This is what list comprehensions are for:
entries = soup.find_all("entry")
accession_numbers = [entry.find("accession-number").text for entry in entries]
Add this line master_list_xml.append(accession_num) in loop, this will create a List.
entries = soup.find_all("entry")
master_list_xml = []
for entry in entries:
accession_num = entry.find("accession-number").text
print(accession_num)
master_list_xml.append(accession_num)
In caluclations.py I have one class called PowerPlant() with
def __init__(self, parameter1, parameter2, parameter3, ...)
and some functions belonging to the class e.g. calculate_supply(self, variable1, variable2).
I'd like to apply the calculations from calculations.py to some power plants stored in a csv file. So far i use the following way...
In simulation.py I read the data from the csv with pd.read_csv()
plant_data = pd.read_csv('plants.csv', sep = ';', index_col = False, encoding = 'latin')
Then i create a list of lists with
# Create list of lists from plant_data DataFrame
list_of_plants = [list(row) for row in plant_data.values]
Afterwards I create an instance of the Class PowerPlant with
## Outer loop: Iterate over all plants
for row in range(len(list_of_plants)):
ElectricityOut = []
Gains = []
...
# Initialise an instance of the plant
MyPowerPlant = PowerPlant(parameter1 = list_of_plants[row][0],
parameter2 = list_of_plants[row][1],
parameter3 = list_of_plants[row][2],
...)
# call some methods from calculations.py
...
Any ideas and suggetions how i could do this in a better and more professional way?
Maybe create a object for each plant?
You can iterate over a list like so, no need for range(len())
for row in list_of_plants:
ElectricityOut = []
Gains = []
...
# Initialise an instance of the plant
MyPowerPlant = PowerPlant(parameter1 = row[0],
parameter2 = row[0],
parameter3 = row[0],
...)
I'm not happy with accessing the list items with [item] e.g.
list_of_plants[row][0]
As far as i know there is no possibility to access lists via names (use dictionaries for that), but whats with namedTuples?
Is it possible to create instances of a class from namedTuples? If so i would change the list to a namedTuple...
Any suggestions?
Using this following example:
For each human in the world I would like to create my own list which I can iterate over..
persons = []
attributes = {}
for human in world:
attributes['name'] = human['name']
attributes['eye_color'] = human['eyes']
persons.append(attributes)
Now when I try to print out each name in my own list:
for item in persons:
print item['name']
They are all the same, why?
You are reusing the same dictionary over and over again. persons.append(attributes) adds a reference to that dictionary to the list, it does not create a copy.
Create a new dictionary in your loop:
persons = []
for human in world:
attributes = {}
attributes['name'] = human['name']
attributes['eye_color'] = human['eyes']
persons.append(attributes)
Alternatively, use dict.copy() to create a shallow copy of the dictionary.
I'm trying to find out what I'm doing wrong here.
I'm trying to build a simple ordered dict inside a loop.
Heres the code:
dTabs = OrderedDict()
for iFolder, folder in enumerate(mtd.GroupedTables):
if folder.Count > 0:
dTabs[folder.Name] = OrderedDict()
for item in folder:
table = item.Table
dTabs[folder.Name] = table.Name
print dTabs
this is the output:
OrderedDict([('YouthSportsTrustSportParents_P', 'KYS_Q8_YouthSportsTrustSportParents_P'), ('YouthSportsTrustSportParents_PM', 'KYS_Q8_YouthSportsTrustSportParents_PM')])
there should be six more values for each key...but im only seeing the last two values for each key.
What am i doing wrong here?
Your inner loop assigns in the same location over and over
dTabs = OrderedDict()
for iFolder, folder in enumerate(mtd.GroupedTables):
if folder.Count > 0:
dTabs[folder.Name] = OrderedDict()
for item in folder:
table = item.Table
dTabs[folder.Name] = table.Name # same location is being updated
print dTabs
you need a list like data structure to hold each "table.Name"
dTabs = OrderedDict()
for iFolder, folder in enumerate(mtd.GroupedTables):
if folder.Count > 0:
dTabs[folder.Name] = []
for item in folder:
table = item.Table
dTabs[folder.Name].append(table.Name)
print dTabs
Your inner for loop:
for item in folder:
table = item.Table
dTabs[folder.Name] = table.Name
overwrites the value of dTabs[folder.Name] each time it goes through-- that is, for each item in folder, folder.Name is the same, and each subsequent item overwrites the last one's entry because it has the same key! I think that you think that you can have more than one value per key, which is not true. Try appending onto the current value for the key, instead of replacing it.
drug_input=['MORPHINE','CODEINE']
def some_function(drug_input)
generic_drugs_mapping={'MORPHINE':0,
'something':1,
'OXYCODONE':2,
'OXYMORPHONE':3,
'METHADONE':4,
'BUPRENORPHINE':5,
'HYDROMORPHONE':6,
'CODEINE':7,
'HYDROCODONE':8}
row is a list.
I would like to set all the members of row[..]='' EXCEPT for those that drug_input defines, in this case it is 0, and 7.
So row[1,2,3,4,5,6,8]=''
If row is initially:
row[0]='blah'
row[1]='bla1'
...
...
row[8]='bla8'
I need:
row[0]='blah' (same as before)
row[1]=''
row[2]=''
row[3]=''
...
...
row[7]='bla7'
row[8]=''
How do I do this?
You could first create a set of all the indexes that should be kept, and then set all the other ones to '':
keep = set(generic_drugs_mapping[drug] for drug in drug_input)
for i in range(len(row)):
if i not in keep:
row[i] = ''
I'd set up a defaultdict unless you really need it to be a list:
from collections import defaultdict # put this at the top of the file
class EmptyStringDict(defaultdict):
__missing__ = lambda self, key: ''
newrow = EmptyStringDict()
for drug in drug_input:
keep = generic_drugs_mapping[drug]
newrow[keep] = row[keep]
saved_len = len(row) # use this later if you need the old row length
row = newrow
Having a list that's mostly empty strings is wasteful. This will build an object that returns '' for every value except the ones actually inserted. However, you'd need to change any iterating code to use xrange(saved_len). Ideally, though, you would just modify the code that uses the list so as not to need such a thing.
If you really want to build the list:
newrow = [''] * len(row) # build a list of empty strings
for drug in drug_input:
keep = generic_drugs_mapping[drug]
newrow[keep] = row[keep] # fill it in where we need to
row = newrow # throw the rest away