This question already has answers here:
"Least Astonishment" and the Mutable Default Argument
(33 answers)
Closed 3 years ago.
I want to group students into two different lists according to the subjects but the function is failing to create different lists. I am aware that the instance of the list created in both cases is the same but I am unable to find a workable solution to the same.
def add_tolist(name, students=[]):
students.append(name)
return students
idc306 = add_tolist('ram')
idc101 = add_tolist('shyam')
idc101 = add_tolist('deepa',idc101)
print idc101, idc306
The results should be :
['shyam', 'deepa'] ['ram']
But its printing :
['ram', 'shyam', 'deepa'] ['ram', 'shyam', 'deepa']
I think the problem was that your program treated the new list as not a distinct new copy, this will fix that.
def add_tolist(name, students=[]):
students1 = students.copy()
students1.append(name)
return students1
idc306 = add_tolist('ram')
idc101 = add_tolist('shyam')
idc101 = add_tolist('deepa',idc101)
print (idc101, idc306)
output: ['shyam', 'deepa'] ['ram']
Related
This question already has answers here:
Apply function to each element of a list
(4 answers)
Closed 12 months ago.
I have a list of Full Names, where Forenames and Surnames are seperated by a comma, for example:
Authors = ['Shakespeare, William', 'Dafoe, Daniel', 'Pilcher, Rosamunde']
I need a new list that contains only the Surnames, not the Forenames:
AuthorsSurname = ['Shakespeare', 'Dafoe', 'Pilcher']
How can I get there? I tried to search the Authors list with
regexAuthors = re.compile(r',$')
AuthorsSurname = (regexAuthors.findall(Authors))
to match all entries until the comma and create a new list, but it says I cannot use "Authors" as an argument here because it is not a string.
(the linked topic did not help)
Authors = ['Shakespeare, William', 'Dafoe, Daniel', 'Pilcher, Rosamunde']
surname = [val.split(",")[0] for val in Authors]
# ['Shakespeare', 'Dafoe', 'Pilcher']
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 1 year ago.
I am working in Python trying to write a function using a list of variables.
Here is the data I am working with:
material_list=['leather', 'canvas', 'nylon']
def materialz(MAT):
MAT=support.loc[(material==MAT)].sum()
for i in enumerate(material_list):
materialz(i)
What I am looking for is to pass in each of the items in the list to the function to produce global variables.
leather=
canvas=
nylon=
Any help would be appreciated!
You could create a dictionary and dynamically assign the key-value pairs there. Such as:
material_list=['leather', 'canvas', 'nylon']
material_dict={}
for i in enumerate(material_list):
material_dict[i]=value #Where i would be the key and value the value in the key-value pair
you can use exec
var = 'hello'
output = hello
exec('var = "world"')
print(var)
output = world
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 5 years ago.
I am having a function in python
def func(dataFrame,country,sex):
varible_name=dataFrame[(dataFrame['land']==country) & (dataFrame['sex']==sex)]
Now, for example, I call this function
func(dataFrame,'England','M')
I want that variable name be England_M instead of variable_name.
You can't do that in Python.
What you can do instead is store the results under a dictionary with key = England_M for instance.
In your case, you could do the following :
def func(dataFrame,country,sex):
tmp = dataFrame[(dataFrame['land']==country) & (dataFrame['sex']==sex)]
variable_name = "{c}_{s}".format(c=country, s=sex)
return dict(variable_name=tmp)
Now using it :
results = func(dataFrame, "England", "M")
print(results['England_M'])
This question already has answers here:
Why does "x = x.append(...)" not work in a for loop?
(8 answers)
Closed 5 years ago.
I currently have a list
outcomes = [('A','B','C','A.B','A.C','B.C','A.B.C')]
and I am trying to loop over it. If one of the "name" in the list contains a A, then I want to create another list called column_names with that name in it.
For instance, if I am looking for As, my returning list would be:
column_names = ['A','A.B','A.C',A.B.C']
I have the following code:
column_names = []
for name in outcomes:
if 'A' in name:
column_names = column_names.append(name)
but it returns:
AttributeError: 'NoneType' object has no attribute 'append'
I checked and both column_names and outcomes are lists so I dont understand why.
my_list=list()
for i in outcomes:
for j in i:
if j.count('A') == 1:
my_list.append(j)
output:
['A', 'A.B', 'A.C', 'A.B.C']
in your code
you used column_names = column_names.append(name) you must use column_names.append(name) instead
This question already has answers here:
Access to value of variable with dynamic name
(3 answers)
Closed 6 years ago.
I am using a function that assigns a variable to equal the value of a randomly chosen key. Here the type is string and print works.
def explore():
import random
random_key = random.choice(explore_items.keys())
found_item = explore_items[random_key]
print type(found_item)
print found_item
Then, I want to use the variable name 'found_item' to call a dictionary of the same name, eg:
print found_item['key_1']
But I get the error, "TypeError: string indices must be integers, not str"
How would I use a string to call a previously defined dictionary that shares the same name?
You can use a variable via its name as string using exec:
dic1 = {'k': 'dic2'}
dic2 = {'key_1': 'value'}
exec('print ' + dic1['k'] + "['key_1']")
Short answer: I don't think you can.
However, if the dictionary explore_items uses the dicts in questions as its keys, this should work.
ETA to clarify:
explore_items = {{dict1}: a, {dict2}:b, {dict3}:c}
random_key= random.choice(explore_items.keys())