Currently I'm testing something in python and trying to figure out if I can change a value in another file. Currently I have this written down :
from items import items
def changingitemamount(name, value):
print(items[name][6])
items[name][6] = items[name][6] + int(value)
print(items[name][6])
def changingitemamounttext():
name = input("What do you want to change?")
value = input("How much do you want to add?")
changingitemamount(name,value)
But whenever I run it and go to add the value i get this error.
items[name][6] = items[name][6] + int(value)
TypeError: 'tuple' object does not support item assignment
A tuple is immutable please convert them into a list and do your operations and then you can revert them back to tuples.
Like :
x = (4,5)
listNumbers = list(x)
print(listNumbers)
y = tuple(listNumbers)
print(x)
Hope this helps.
Related
I got data samples like this:
[1.212,3.54,[4.123],[5.5343],[[2,3.2],[9.345,4.102]]]
((1.41231,3.312),4.212,6.312)
["hello",1.232,"3.555"]
my final purpose is serialize those datas, but some data in those lists isn't python types,like python float--sympy.Core.Float , so I must read those multidimensional arrays,find out those number which is Sympy.core.Float type, then doing a type converts like this: "float(number)",so is there a easy to finish this ?
Here is part codes:
def RecursData(datas,final_list):
for index ,value in enumerate(datas):
if(isinstance(value,(tuple,list))):
tmp_data_list = list(value)
RecursData(tmp_data_list,final_list)
elif isinstance(value,(float,Float)):
final_list.append(float(value))
else:
final_list.append(value)
In your case i would do this:
your_data = [1.212,3.54,[4.123],[5.5343],[[2,3.2],[9.345,4.102]]]
def itter(lst):
end_goal = []
for x in lst:
if hasattr(x, '__iter__'):
end_goal.append(itter(x))
else:
# here do whatever you need to do
# so if you have to reconvert data
if isinstance(x,Float):
x = float(x)
end_goal.append(x)
return end_goal
# then just run the function/
print(itter(your_data))
this will replace all Float values to python floats
I have a nested list with elements. I want the user to remove one list when he/she types an index of the list: So let's say the user types: "0" so ['elem', 'elem1', 'elem2'] will be deleted.
0 ['elem', 'elem1', 'elem2']
1 ['elem3', 'elem4', 'elem5']
2 ['elem6', 'elem7', 'elem8']
3 ['elem9', 'elem', 'elem10']
My code works without the function, but when I try to create a function, I receive an error that I don't understand.
TypeError: 'NoneType' object cannot be interpreted as an integer
database = [['elem', 'elem1', 'elem2'],
['elem3', 'elem4', 'elem5'],
['elem6', 'elem7', 'elem8'],
['elem9', 'elem', 'elem10']]
def remove_from_database(index):
if index in database:
database.pop(index)
return index
else:
print("not here")
for index, elem in enumerate(database):
print(index, elem)
user = remove_from_database(int(input("type in the index to remove: ")))
result = database.pop(user)
print(f"removed: {result}")
Could someone please tell me what this error means? Does it mean that the index is not actually an int? How can I fix it?
Your problem is with your "def remove_from_database(index)".
You check for the "0" in the database - Of course it will not be there.
If you rewrite your method like this, it will work:
def remove_from_database(index):
try:
database.pop(index)
except:
print("Not in here")
You had few mistakes. You've tried to pop elements again from database outside method, your if compare won't work right.
database = [['elem', 'elem1', 'elem2'],
['elem3', 'elem4', 'elem5'],
['elem6', 'elem7', 'elem8'],
['elem9', 'elem', 'elem10']]
def remove_from_database(index):
if index < len(database):
return database.pop(index)
else:
print("not here")
return None
for index, elem in enumerate(database):
print(index, elem)
user = int(input("type in the index to remove: "))
result = remove_from_database(user)
print(f"removed: {result}")
#in older Python ver
#print("removed: {0}".format(result))
Instead of if else, you can also use #Markus sugestion and it should work even better.
It doesn't want to print out the list entered by the user. I think the problem is in list= []
from HeapClass import Heap
def minHeap(list):
heap = Heap() #
lst = eval(input("Enter list of numbers: "))
for v in lst:
heap.add(v)
for i in range(len(list)):
list[len(list) - 1 - i] = heap.remove()
def main():
list = [] This think the problem is here because it doesn't return a list but when I write list = lst... It does not work either
minHeap(list)
for v in list:
print(str(v)+ " ", end = " ")
main()
You're using list as a variable name. Rename it to something else here def minHeap(list):, here def main(): list = [] and everywhere else. You don't need it.
Also, you don't need the evil eval() :)
If you want user input of the format "1,2,3" (comma-separated numbers) to be cast to a list of integers, you could instead do:
lst = list(input("Enter list of numbers: ")) in python2.7
or
lst = [int(x) for x in input("Enter list of numbers: ").split(",")] in python3.
To see why using list as a variable name is bad/confusing, try the following:
Type list((1,2,3)) in your interpreter. It should transform the tuple (1,2,3) to a list and return [1, 2, 3]. All is well.
Now try typing list = [] and repeat list((1,2,3)).
You should now get an error saying TypeError: 'list' object is not callable and you won't be able to cast anything to list again; it effectively overrides the datatype so what used to be <type 'type'> is now a single list of <type 'list'>. Overriding built-in stuff gets weird; best to avoid it unless you're intentionally doing meta-programming.
so I have a class with a list, and I would like to add a number to all the elements of that list, but not to every list in the class. I tried this:
class class_name:
def __init__(self,list_name,other_list):
self.list_name = list_name
self.other_list = other_list
list1 = [1.0,2.0,3.0,4.0]
list2 = [4.0,5.0,6.0,7.0]
data = [0]*len(list1)
for i,(l1,l2) in enumerate(zip(list1,list2)):
data[i] = class_name(l1,l2)
[(x + 5.0).list_name for x in data]
and it gives me the error:
TypeError: unsupported operand type(s) for +: 'instance' and 'float'
edit: people seem to not understand what I want. In the real code I have, the lists have been added to a class (in this case data) which I've been working with, but one of the lists in the class (specifically referring to magnitudes) needs to be calibrated. I do this by adding a number to every element in that list to calibrate it. This has to be done to the list connected to the class it's in, so I can't edit the list before putting it into the class.
I already have this class created much earlier in my code, and I needed it to be the way it was before so that I could work with all the elements. Now, later in the code, I want to calibrate this magnitude list within the class. Is there a way to do that?
maybe this attempt better illustrates what I'm trying to do:
[x.list_name for x in data] = [x.list_name+5 for x in data]
this also doesn't work, I get this error:
SyntaxError: can't assign to list comprehension
I just feel like it makes people understand what I need.
Check out the Map function for python.
https://docs.python.org/2/tutorial/datastructures.html#functional-programming-tools
class class_name:
def __init__(self,list_name,other_list):
self.list_name = list_name
self.other_list = other_list
list1 = [1.0,2.0,3.0,4.0]
list2 = [4.0,5.0,6.0,7.0]
def add_five(x): return x+5
list1 = map(add_five, list1)
#or instead you can use a lambda
list1 = map(lambda x: x+5 , list1)
EDIT: maybe try this.
for class_name in class_names:
class_name.list_name = map(lambda x: x+5 , class_name.list_name)
If you want to increment one of two lists stored as a list of pairs, this should work:
[x.list_name+5.0 for x in class_names]
x isn't a number, it's the class_name object. You want to retrieve the thing you want to increment from x (x.list_name) and then add 5.0.
You are adding the value to the instance first then accessing the attribute.
class class_name:
def __init__(self,list_name,other_list):
self.list_name = list_name
self.other_list = other_list
list1 = [1.0,2.0,3.0,4.0]
list2 = [4.0,5.0,6.0,7.0]
class_names = [0]*len(list1)
for i,(l1,l2) in enumerate(zip(list1,list2)):
class_names[i] = class_name(l1,l2)
print [x.list_name+5.0 for x in class_names]
I am not sure what you mean, but I have created a simple example:
class class_name(object):
def __init__(self,list_name,other_list):
self.list_name = list_name
self.other_list = other_list
self.list1 = []
self.list2 = []
self.list1.append(self.list_name)
self.list2.append(self.other_list)
print "My List1: ", self.list1
print "My List2: ", self.list2
def input_data():
list_one = raw_input("Data for list 1: ")
list_two = raw_input("Data for list 2: ")
class_name(list_one, list_two)
if __name__ == '__main__':
input_data()
Is that what you want to?
I'm trying to make a function that will take an arbritrary number of dictionary inputs and create a new dictionary with all inputs included. If two keys are the same, the value should be a list with both values in it. I've succeded in doing this-- however, I'm having problems with the dict() function. If I manually perform the dict function in the python shell, I'm able to make a new dictionary without any problems; however, when this is embedded in my function, I get a TypeError. Here is my code below:
#Module 6 Written Homework
#Problem 4
dict1= {'Fred':'555-1231','Andy':'555-1195','Sue':'555-2193'}
dict2= {'Fred':'555-1234','John':'555-3195','Karen':'555-2793'}
def dictcomb(*dict):
mykeys = []
myvalues = []
tupl = ()
tuplist = []
newtlist = []
count = 0
for i in dict:
mykeys.append(list(i.keys()))
myvalues.append(list(i.values()))
dictlen = len(i)
count = count + 1
for y in range(count):
for z in range(dictlen):
tuplist.append((mykeys[y][z],myvalues[y][z]))
tuplist.sort()
for a in range(len(tuplist)):
try:
if tuplist[a][0]==tuplist[a+1][0]:
comblist = [tuplist[a][1],tuplist[a+1][1]]
newtlist.append(tuple([tuplist[a][0],comblist]))
del(tuplist[a+1])
else:
newtlist.append(tuplist[a])
except IndexError as msg:
pass
print(newtlist)
dict(newtlist)
The error I get is as follows:
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
dictcomb(dict1,dict2)
File "C:\Python33\M6HW4.py", line 34, in dictcomb
dict(newtlist)
TypeError: 'tuple' object is not callable
As I described above, in the python shell, print(newtlist) gives:
[('Andy', '555-1195'), ('Fred', ['555-1231', '555-1234']), ('John', '555-3195'), ('Karen', '555-2793')]
If I copy and paste this output into the dict() function:
dict([('Andy', '555-1195'), ('Fred', ['555-1231', '555-1234']), ('John', '555-3195'), ('Karen', '555-2793')])
The output becomes what I want, which is:
{'Karen': '555-2793', 'Andy': '555-1195', 'Fred': ['555-1231', '555-1234'], 'John': '555-3195'}
No matter what I try, I can't reproduce this within my function. Please help me out! Thank you!
A typical example of why keywords should not be used as variable names. Here dict(newtlist) is trying to call the dict() builtin python, but there is a conflicting local variable dict. Rename that variable to fix the issue.
Something like this:
def dictcomb(*dct): #changed the local variable dict to dct and its references henceforth
mykeys = []
myvalues = []
tupl = ()
tuplist = []
newtlist = []
count = 0
for i in dct:
mykeys.append(list(i.keys()))
myvalues.append(list(i.values()))
dictlen = len(i)
count = count + 1
for y in range(count):
for z in range(dictlen):
tuplist.append((mykeys[y][z],myvalues[y][z]))
tuplist.sort()
for a in range(len(tuplist)):
try:
if tuplist[a][0]==tuplist[a+1][0]:
comblist = [tuplist[a][1],tuplist[a+1][1]]
newtlist.append(tuple([tuplist[a][0],comblist]))
del(tuplist[a+1])
else:
newtlist.append(tuplist[a])
except IndexError as msg:
pass
print(newtlist)
dict(newtlist)
You function has a local variable called dict that comes from the function arguments and masks the built-in dict() function:
def dictcomb(*dict):
^
change to something else, (*args is the typical name)
Do you need to implement this entirely yourself, or would it be okay to use defaultdict? If so, you might do something like:
from collections import defaultdict
merged_collection = defaultdict(list)
collection_1= {'Fred':'555-1231','Andy':'555-1195','Sue':'555-2193'}
collection_2= {'Fred':'555-1234','John':'555-3195','Karen':'555-2793'}
for collection in (collection_1, collection_2):
for name, number in collection.items():
merged_collection[name].append(number)
for name, number in merged_collection.items():
print(name, number)
John ['555-3195']
Andy ['555-1195']
Fred ['555-1231', '555-1234']
Sue ['555-2193']
Karen ['555-2793']