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 = []
Related
So I wrote this code to return back every string in the given lst: list once. Here is my code
def make_unique(lst: list[str]):
s = []
for x in lst:
if lst.count(x) == 1:
s.append(x)
else:
return(x)
return s
When I put in the input:
print(make_unique(lst=['row','mun','row']))
The output returns
row
but I want my output to return
['row','mun']
which is basically all the strings in the list printed once.
How can I do this??
Why not you try this one line short code to remove duplicates from your list and make it unique
def make_unique(lst):
return list(dict.fromkeys(lst))
print(make_unique(['row','mun','row'])) #['row','mun']
Easy way to do this is turn the list into a set. A set only shows each item once and thats what you want.
lst=['row','mun','row']
setLst = set(lst)
for elem in setLst:
print(elem)
You can use set.
lst=['row','mun','row']
print(set(lst))
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")]
I am trying to find the max of the "rollList" and everything I have tried isn't working.I'm not very good with coding and the instruction my teacher gave me isn't very clear. I also have to reset "rollList" back to empty for each player and I am very confused.Please someone help.
import random
class Player:
def __init__(self,name ):
self.name = name
self.dice = []
def __str__(self):
return self.name
def roll_Dice(self):
rollDice = random.randint(1, 6)
return rollDice
rounds = 1
rollList = []
newplayer = []
newplayer.append(Player("CAT:"))
newplayer.append(Player("DOG:"))
newplayer.append(Player("LIZARD:"))
newplayer.append(Player("FISH:"))
for rounds in range(1,4):
print("-----------------")
print("Round" + str(rounds))
for p in newplayer:
print(p)
for x in range (4-rounds):
rollDice = random.randint(1, 6)
rollList.append(rollDice)
print(rollList)
max.pop(rollList)
print(rollList)
rollList.clear()
len(rollList)
The line max.pop(rollList) is fairly meaningless. It attempts to call the pop method of the built-in max function, which doesn't exist.
You can get the maximum by just calling max itself:
maxRoll = max(rollList)
If you want to remove that roll, you can (although it doesn't seem necessary, since you'll be clearing the list):
rollList.remove(maxRoll)
If you want to append the maximum to another list:
anotherList.append(maxRoll)
You can find the maximum of a list using max() function:
mylist = [1,2,4,5,6,7,-2,3]
max_value = max(mylist)
Now max_value is equal to 7. You can add this to a new list using append() method:
new_list = []
new_list.append(max_value)
then new_list will be [7]
I report some suggestions to resolve the error I suppose you have: AttributeError: 'builtin_function_or_method' object has no attribute 'pop'
Just change max.pop(rollList) to max(rollList).
Then you have a list of only one element because you are calling methods inside the for rounds in range(1,4): loop, without letting the list populate with other elements. You are calling also clear at each loop.
Also, the for x in range (4-rounds): it is not required, it's a nested loop.
You are printing the list of names without assign to each person the value of roll dice, so who's the winner?
Finally, you defined roll_Dice() as instance method of Person, so why not use it?
So, why not rollList.append(p.roll_Dice()) instead of:
rollDice = random.randint(1, 6)
rollList.append(rollDice)
Hope this can help.
I want every element in l(which is a list) to be added to a.
When I run the function, it gives me '[]' every time. How can I fix this?
def sim(l):
a = []
if len(l)>0:
a = a.append(l.pop())
l.pop()
return sim(l)
return a
Several things are wrong:
You shouldn't use lowercase L for a variable name - it looks like one
At the top of the function you assign an empty list to a - ultimately sim will be called with an empty list, then a will be assigned an empty list, the conditional statement will fail and sim will return an empty list.
Inside the conditional statement you assign the return value of list.append() to a. The return value is None so whatever a was before, it gets wiped out.
Inside the conditional statement you pop() two items out of your control list
An empty list has a boolean value of false so there is no need to explicitly check its length,
def sim(el, a = None):
if el:
a.append(el.pop())
return sim(el, a)
return a
I was taught to write the base case of a recursive function as the first statement:
def sim(el, a = None):
if not el:
return a
a.append(el.pop())
return sim(el, a)
append() doesn't return anything but does update the existing list. In other words, by trying to assign the result of the append() method, you're setting a to nothing after you have already appended the item.
Your Code :def sim(l):
a = []
when you call Function recursively return sim(l) every time it is call sim(l) and a=[] is empty.
Try This :
def sim(l,a):
if len(l)>0:
a.append(l.pop())
print a
return sim(l,a)
return a
Is this a homework assignment where you're required to do it in a certain (overly complicated) way? Because if not, you can add one list to another in Python like so:
>>> l = [1, 2, 3]
>>> a = []
>>> a.extend(l)
>>> a
[1, 2, 3]
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.