can you help me with python parameters. i have problem with string #4. thank you
output is list[2]
but i need BMW
list = ["Ford", "Volvo", "BMW"]
x = len(list)
a = x - 1
car = 'list[%s]' % a
print car
It's simple. you have to do only car = list[a] which will give you 'BMW'.
myList = ["Ford", "Volvo", "BMW"]
x = len(myList)
a = x - 1
car = myList[a]
print(car) # 'BMW'
I have renamed the variable name. While you are giving variable name just careful about the predefined/built in keywords because its not good approach to give variable/function name same as built in types as it masks the builtin type name.
At first, don't use list as a variable, list is a keyword in python. Try some other name. And you are now printing the value of a which is an index not an element of the list. You have to use list[a] to print an element of a list positioned at index a.
Related
So the problem I have is I think that the code is good, but it doesn't work as I would like it to.
Make a program that filters a list of strings and returns a list with only your friends name in it.
If a name has exactly 4 letters in it, you can be sure that it has to be a friend of yours! Otherwise, you can be sure he's not...
Ex: Input = ["Ryan", "Kieran", "Jason", "Yous"], Output = ["Ryan", "Yous"]
The code I wrote:
def friend(x):
for x in friend:
split_words = x.split( )
word_count = len(split_words):
if word_count = 4:
print(x)
Thanks in advance!
Iterate over the list of names.
Check each name's length: Using the helper function is_friend.
Collect the name if it is a friend in a list.
Print the resulting list.
Input = ["Ryan", "Kieran", "Jason", "Yous"]
def is_friend(name):
return len(name) == 4
friends = []
for name in Input:
if is_friend(name):
friends.append(name)
print(friends)
Or a shorter version using list comprehension:
friends = [name for name in Input if len(name) == 4]
print(friends)
I have one list like this list = [] and in this list there are elements like this
15,a,90 -
16,c,60 -
17,e,50 -
The output of the list[0] is 15,16,17 and i have code like this
ogrno = input("a")
for i in ogr.list:
if ogrno == i[0]:
add = [input("new number "),input("new word"),input("new number")
i = add
I want to add a new list instead of the selected line here.But "i" not used.
This fails for the same reason that a = 3; i = a; i = 2 doesn't change the value of a: assigning to a name never affects the object currently bound to that name. If you want to change what a list references, you need to assign to the list slot itself.
for i, value in enumerate(ogr.list):
if ogrno == value[0]:
ogr.list[i] = [input("new number "),input("new word"),input("new number")]
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 need to sort items in a tuple using the bubble sort method for a project in my computer science class. The items are all integers.
SwapAgain = True
while SwapAgain == True:
SwapAgain = False
for item in xrange(len(mytuple)):
if mytuple[item] > mytuple[item + 1]:
SwapAgain = True
temp = mytuple[item]
mytuple[item] = mytuple[item + 1]
mytuple[item + 1] = temp
return mytuple
I'm trying to assign the value of one item in the tuple to another, but when I try the code above I get this error:
mytuple[item] = mytuple[item + 1]
TypeError: 'tuple' object does not support item assignment
I would have preferred to use a list, but my teacher only provided us with a specific tuple. I really appreciate any help I can get. Thanks!
A tuple is an immutable data type. Once you create it, you can't alter it. So doing this with a list would make sense, and you have the option to return a tuple when the sorting is done, for example:
SwapAgain = True
myList = list(myTuple)
while SwapAgain == True:
SwapAgain = False
for i in xrange(len(myList)):
if myList[i] > myList[i + 1]:
SwapAgain = True
temp = myList[i]
myList[i] = myList[i + 1]
myList[i + 1] = temp
return myList # or return tuple(myList) if you want
tuple is fixed structure in python, as the complier told you 'tuple' object does not support item assignment. you should copy it to a new list
As the condition with you is that you have to use a tuple according to your teacher, what would be the best possible solution is that, change the tuple to a list
temp_list = list(myTuple)
perform the bubble sort on the list and then again change the sorted list to a tuple
final_tuple = tuple(temp_list)
So, finally you are going to get a sorted tuple.
Tuple's are immutable so you can set new values or remove items, But if your teacher has specifically asked for tuple then you can create an another tuple called sorted or something where you add these new items and finally replace the original tuple with this one.
var_list = [one, two, three]
num = 1
for var in var_list:
var = num
num += 1
The above gives me an error that 'one' doesn't exist. Can you not assign in this way? I want to assign an incrementing number for each var in the list. So I want the equivalent of
one = 1
two = 2
three = 3
but without having to manually create and initialize all variables. How can I do this?
You can access the dictionary of global variables with the globals() built-in function. The dictionary uses strings for keys, which means, you can create variables with names given as strings at run-time, like this:
>>> var_names = ["one", "two", "three"]
>>> count = 1
>>> for name in var_names:
... globals()[name] = count
... count += 1
...
>>> one
1
>>> two
2
>>> three
3
>>> globals()[raw_input()] = 42
answer
>>> answer
42
Recommended reading
Python variables are names for values. They don't really "contain" the values.
for var in var_list: causes var to become a name for each element of the list, in turn. Inside the loop, var = num does not affect the list: instead, it causes var to cease to be a name for the list element, and instead start being a name for whatever num currently names.
Similarly, when you create the list, if one, two and three aren't already names for values, then you can't use them like that, because you are asking to create a list of the values that have those names (and then cause var_list to be a name for that list). Note that the list doesn't really contain the values, either: it references, i.e. shares them.
No, it doesn't work like that.
You can try:
one, two, three = range(1, 4)
This work by defining the variables in a multiple assignment. Just as you can use a, b = 1, 2. This will unroll the range and assign its values to the LHS variables, so it looks like your loop (except that it works).
Another option (which I wouldn't recommend in a real program...) would be to introduce the variable names in an exec statement:
names = ['one', 'two', 'three']
num = 1
for name in names:
exec "%s = %s" % (name, num)
num += 1
print one, two, three
A variable doesn't exist until you create it. Simply referencing a variable isn't enough to create it. When you do [one, two, three] you are referencing the variables one, two and three before they are created.
I would simply use list comprehension.
one, two, three = range(1, 4)
one, two, three = [val for val in ['one', 'two', 'three']]
v1, v2, v3 = [func(idx) for idx in range(1, 4)]