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")]
Related
I need help fixing this code. My goal is to change the last element of the indexed string from "3" to "F" if the two indexes before are an even integer.
change = ['E013', 'E023', 'E033', 'E042', 'E054']
def help():
for i in change:
test = int(i[1:3])
if test % 2 == 0 and i[3] == "3":
subs = [i.replace("3","F") for i in change]
print(subs)
help()
So for example if you have a list:
INPUT
change = ['E013', 'E023', 'E033', 'E042', 'E054']
I want this to output:
OUTPUT
change = ['E013', 'E02F', 'E033', 'E042', 'E054']
Right now my code is outputting:
['E01F', 'E02F', 'E0FF', 'E042', 'E054']
You have to change just one of the elements in the list, not all of them:
change = ["E013", "E023", "E033", "E042", "E054"]
for index, value in enumerate(change):
test = int(value[1:3])
print(f"doing {index} {value} {test}")
if test % 2 == 0 and value[3] == "3":
print(f"changing index {index}")
# strings are immutable in python, and .replace creates a new one
# which has to be assigned in the list
change[index] = value.replace("3", "F")
print(change)
Note that I left the test value[3] == "3" that you had, so E042 is not modified, as it does not end with 3. If you only need to check if the number is even, remove that.
Cheers!
I am trying to empty a nested list in a python script:
deadBody_inv = [['AK47', 30],['M16', 30],['FragGrenade', 5],['Hunting Knife', 1]]
def search_body(deadBody):
option = str(input("""\n\nYou enter the destroyed
bunker to find a dead enemy soldier./n
A).Dispose Body
B).Search Body \n\n...>"""))
if option.lower() == 'a':
inv_len = len(deadBody)
for k in range(0, inv_len):
inv_len.remove(k)
I keep getting this error:
AttributeError: 'int' object has no attribute 'remove'
im sure I am doing this wrong, I'm simply trying to remove each value of the list within a list. I figured the for loop would iterate through each
list value(store it in k) and use the .remove() method to remove each value
what am I doing wrong?
Use this:
if option.lower() == 'a':
items = []
while len(deadBody) > 0:
items.append(deadBody.pop())
The array items will contain all of the items looted from deadBody
Additionally, if you have a list for the player's inventory, just use
player.extend(deadBody)
deadBody = [] # or alternatively, del deadBody
inv_len = len(deadBody)
This is equal to the length of deadBody. Just use something that empties dead body and if you want to add them to your inventory. Such as:
player_inv.extend(deadBody)
deadBody.clear() #deadBody is now an empty list
You're storing an int in inv_len then telling it to remove from the int.
I think you're trying to remove all items from deadBody, if you want do that just reassign deadBody to an empty list.
deadBody = []
When assigning a python string format return value like '67.67.%s.%s' % (str(j), str(i)), it is inconsistent between assigning to a key of a dict and assigning to a key in a sub-dict of a dict.
For example:
i = 0
j = 1
dict_template = {"id": "1", "another_dict": {"value": "hello"}}
dict_list = []
for idx in list(range(2, 1002)):
new_dict = copy.copy(dict_template)
new_dict['id'] = 'obj_id_%s' % str(idx)
new_dict['another_dict']['value'] = '67.67.%s.%s' % (str(j), str(i))
dict_list.append(new_dict)
if i < 254:
i += 1
else:
j += 1
i = 1
In this example, every new_dict['another']['value'] would be the same string and have the same id.
However, if I change this line new_dict['another_dict']['value'] = '67.67.%s.%s' % (str(j), str(i)) to new_dict["another_dict"] = '67.67.%s.%s' % (str(j), str(i)), each new_dict["another_dict"] would have different values.
By the way I'm using Python 3.4.3.
copy.copy performs a shallow copy of the given argument. That means that it creates a new dict and adds to it references (not copies) to everything that was already in the first dict. For immutable things like strings and numbers, there's no problem. But each instance is pointing to the same (mutable) inner dictionary.
Instead, you need to use copy.deepcopy. It'll recursively create new copies for every attribute of the template argument.
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.
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.