Declare an empty surface variable in pygame? [duplicate] - python

list1 = ["name1", "info1", 10]
list2 = ["name2", "info2", 30]
list3 = ["name3", "info3", 50]
MASTERLIST = [list1, list2, list3]
def printer(lst):
print ("Available Lists:")
for x in range(len(lst)):
print (lst[x])[0]
This code is returning the "'NoneType' object is not subscriptable" error when I try and run
printer(MASTERLIST)
What did I do wrong?

The print() function returns None. You are trying to index None. You can not, because 'NoneType' object is not subscriptable.
Put the [0] inside the brackets. Now you're printing everything, and not just the first term.

The [0] needs to be inside the ).

Don't use list as a variable name for it shadows the builtin.
And there is no need to determine the length of the list. Just iterate over it.
def printer(data):
for element in data:
print(element[0])
Just an addendum: Looking at the contents of the inner lists I think they might be the wrong data structure. It looks like you want to use a dictionary instead.

Point A: Don't use list as a variable name
Point B: You don't need the [0] just
print(list[x])

The indexing e.g. [0] should occour inside of the print...

list1 = ["name1", "info1", 10]
list2 = ["name2", "info2", 30]
list3 = ["name3", "info3", 50]
def printer(*lists):
for _list in lists:
for ele in _list:
print(ele, end = ", ")
print()
printer(list1, list2, list3)

Related

Python list - call function with different values

def check(val, list=[]):
list.append(val)
return list
list1=check("a")
list2=check("b",[])
list3=check("c")
If I run list1 and check the output it shows ["a"]
But, If I run list1, list2 and list3 in one
cell and check for list1 it shows ['a','c'], can someone please explain why is it so?
This is the right way to do this:
def check(val, values=None):
if values is None:
values = []
values.append(val)
return values
list1 = check("a")
list2 = check("b", [])
list3 = check("c")
Default argument values should not be mutable. You can find a good explanation here,
And list is a poor name for a variable, because list is a built-in type, as are str, set, dict.
It seems that list1 and list3 share same object.
You can try this:
def check(val, list=[]):
list.append(val)
print(hex(id(list)))
return list
list1=check("a")
list2=check("b")
list3=check("c")
print(list1)
print(list2)
print(list3)

Find Numbers in a List Consisting of Strings and Convert them to Floats

I'm trying to do an exercise where I have a list:
list_1 = ['chocolate;1.20', 'book;5.50', 'hat;3.25']
And I have to make a second list out of it that looks like this:
list_2 = [['chocolate', 1.20], ['book', 5.50], ['hat', 3.25]]
In the second list the numbers have to be floats and without the ' '
So far I've come up with this code:
for item in list_1:
list_2.append(item.split(';'))
The output looks about right:
[['chocolate', '1.20'], ['book', '5.50'], ['hat', '3.25']]
But how do I convert those numbers into floats and remove the double quotes?
I tried:
for item in list_2:
if(item.isdigit()):
item = float(item)
Getting:
AttributeError: 'list' object has no attribute 'isdigit'
list_1 = ['chocolate;1.20', 'book;5.50', 'hat;3.25']
list_2 = [x.split(';') for x in list_1]
list_3 = [[x[0], float(x[1])] for x in list_2]
item is a list like ['chocolate', '1.20']. You should be calling isdigit() on item[1], not item. But isdigit() isn't true when the string contains ., so that won't work anyway.
Put the split string in a variable, then call float() on the second element.
for item in list_1:
words = item.split(';')
words[1] = float(words[1])
list_2.append(words)
I don't know if this helpful for you.
But,I think using function is better than just using simple for loop
Just try it.
def list_map(string_val,float_val):
return [string_val,float_val]
def string_spliter(list_1):
string_form=[]
float_form=[]
for string in list_1:
str_val,float_val=string.split(";")
string_form.append(str_val)
float_form.append(float_val)
return string_form,float_form
list_1 = ['chocolate;1.20', 'book;5.50', 'hat;3.25']
string_form,float_form=string_spliter(list_1)
float_form=list(map(float,float_form))
output=list(map(list_map,string_form,float_form))
print(output)
Your way of creating list_2 is fine. To then make your new list, you can use final_list = [[i[0], float(i[1])] for i in list_2]
You could also do it in the for loop like this:
for item in list_1:
split_item = item.split(';')
list_2.append([split_item[0], float(split_item[1])])
This can be achieved in two lines of code using list comprehensions.
list_1 = ['chocolate;1.20', 'book;5.50', 'hat;3.25']
list_2 = [[a, float(b)] for x in list_1 for a, b in [x.split(';', 1)]]
The second "dimension" to the list comprehension generates a list with a single sublist. This lets us essentially save the result of splitting each item and then bind those two items to a and b to make using them cleaner that having to specify indexes.
Note: by calling split with a second argument of 1 we ensure the string is only split at most once.
You can use a function map to convert each value.
def modify_element(el):
name, value = el.split(';')
return [name, float(value)]
list_1 = ['chocolate;1.20', 'book;5.50', 'hat;3.25']
result = list(map(modify_element, list_1))
For a problem like this you can initialize two variables for the result of calling the split function and then append a list of both values and call the builtin float function on the second value.
array = []
for i in a_list:
string, number = i.split(";")
array.append([string, float(number)])
print(array)

Upon shuffling I get a None object. What is wrong?

I have shuffled the list and assigned it to another variable and when I am trying to print it, it is giving output as None? What is wrong ?
list1 = [1,2,3,4,5,6]
list2 = shuffle(list1)
print list2
The random.shuffle() function is designed to take a list and shuffle its contents. It does not return the shuffled list. The documentation states:
Shuffle the sequence x in place.
As such, if you try to assign the return to a variable you will get None.
You can do the following instead:
list1 = [1,2,3,4,5,6]
shuffle(list1)
print list1
If you wish to preserve your original list order:
list1 = [1,2,3,4,5,6]
list2 = list1[::] # make a copy
shuffle(list2)
print list2
Shuffle() function is not accessible directly, so we need to import shuffle module and then we need to call this function using random static object.
#!/usr/bin/python
import random`
list = [1, 2, 3, 4, 5];
random.shuffle(list)
print "list : ", list

iterating over two lists to create a new list in Python

I'm trying to iterate over two lists to populate a new list with the outcome, but am not sure where it's going wrong. Note: i'm a beginner using Python. Mahalo in advance!
sumList = [27400.0, 32900.0, 42200.0, 40600.0];
volList = [27000.0, 40000.0, 31000.0, 40000.0];
rendeList = [];
x = 0;
for sumValue in range (0, len(sumList)-1):
rendeList = rendeList.append((sumList[x]/volList[x])*100)
x += 1;
However, I get an Attribute Error: 'NoneType' object has no attribute 'append'. After running the for loop, i get:
print rendeList
None
My expected outcome would have been:
print rendeList
[101.48, 82.25, 136.13, 101.49]
list.append(x) modifies the list and returns None.
Change your code to:
for sumValue in range (0, len(sumList)):
rendeList.append((sumList[x]/volList[x])*100)
x += 1
Or simplify it to:
for sumValue, volValue in zip(sumList, volList):
rendeList.append((sumValue / volValue) * 100)
Here is your solution using list comprehension:
result = [a[0]/a[1]*100 for a in zip(sumList, volList)]
The root of your problem is that list.append returns None
>>> a_list = list('abc')
>>> print(a_list.append('d'))
None
>>> a_list
['a', 'b', 'c', 'd']
And if you reassign a_list:
>>> a_list = a_list.append('e')
>>> a_list
>>> print(a_list)
None
Python's map function would be perfect for this:
rendeList = map(lambda x,y: x/y*100, sumList, volList)
The map function returns a list where a function (the first argument, which here I've supplied as a Lambda expression) is applied to each element of the passed in list, or in this case each pair of elements from the two lists passed in.

Python: Removing a single element from a nested list

I'm having trouble figuring out how to remove something from within a nested list.
For example, how would I remove 'x' from the below list?
lst = [['x',6,5,4],[4,5,6]]
I tried del lst[0][0], but I get the following result:
TypeError: 'str' object doesn't support item deletion.
I also tried a for loop, but got the same error:
for char in lst:
del char[0]
Use the pop(i) function on the nested list. For example:
lst = [['x',6,5,4],[4,5,6]]
lst[0].pop(0)
print lst #should print [[6, 5, 4], [4, 5, 6]]
Done.
Your code works fine. Are you sure lst is defined as [['x',6,5,4],[4,5,6]]? Because if it is, del lst[0][0] effectively deletes 'x'.
Perhaps you have defined lst as ['x',6,5,4], in which case, you will indeed get the error you are mentioning.
You can also use "pop". E.g.,
list = [['x',6,5,4],[4,5,6]]
list[0].pop(0)
will result in
list = [[6,5,4],[4,5,6]]
See this thread for more: How to remove an element from a list by index in Python?

Categories

Resources