Having an error where i'm trying to get the first work from a string that is passed in to a method within a class. But i am getting AttributeError: 'Deck' object has no attribute 'split' when I run. The 'new_card' that is passed in will be for example 'Two of Hearts'. and new_Card is a string and self.values is a dictionary
# returns integer value of a card
def get_card_value(self, new_card):
return self.values[new_card.split()[0]]
and the error:
Traceback (most recent call last):
File "/home/andypaling/Documents/Programming/python/random/card_game/game.py", line 146, in
if not Game.check_same_cards(player1_deck, player2_card):
File "/home/andypaling/Documents/Programming/python/random/card_game/game.py", line 87, in check_same_cards
if card1.get_card_value(card1) == card2.get_card_value(card2):
File "/home/andypaling/Documents/Programming/python/random/card_game/game.py", line 40, in get_card_value
split_string = new_card.split(' ')
thanks for any help
Hey it seems like you are using a diffrent data type and not a string in your case judging that your making a card game i am guessing you are using a tuple. Try converting the data to a string then split it using the .split() function.
I hope this can help.
Related
I'm trying to program a reddit bot, but get this error message:
Traceback (most recent call last):
File "main.py", line 64, in <module>
run_bot(r, comments_replied_to)
File "main.py", line 34, in run_bot
comments_replied_to.append(comment.id)
AttributeError: 'filter' object has no attribute 'append'
Here is my code: https://pastebin.com/caz14jm7
I think I have to change append into a list, but I don't know how to do that
Part of this is a version difference. In Python 2, filter returned a list. In Python 3, filter returns a generator, which you are treating like a list. The filter generator does not have an append method.
So, you just need to turn it into a list:
comments_replied_to = list(filter(None, comments_replied_to))
Or, even better (in the opinion of many):
comments_replied_to = [k for k in comments_replied_to if k]
I have 2 potential solutions for you,
solution 1:
Line 55 You can change like this
comments_replied_to = List(filter(None, comments_replied_to))
so that, your get_saved_comments() will return a list.
This will help you use the append method and comments_replied_to.append(comment.id) should work without any error
Solution 2:
Line 60: You can change like this
comments_replied_to = list(get_saved_comments())
As long as comments_replied_to is a list type, it will allow you to append method without any issues.
check this blog to have a better understanding over append method
https://www.programiz.com/python-programming/methods/list/append
I have captured a string from a REST get request and have placed it in a variable. The string is:
{"name":"na1mailboxarchive","objectCount":49564710,"dataBytes":36253526882451},{"name":"na1mailboxarchive2","objectCount":17616567,"dataBytes":13409204616615}
I am trying to convert it to a dictionary so I can increment through it and capture the bucket name, size and object count. I have tried eval()
bucket_dict = eval(bucket_info)
but the program errors out with a:
Traceback (most recent call last):
File "./test.py", line 83, in <module>
for k,b in bucket_dict.items():
AttributeError: 'tuple' object has no attribute 'items'
When I print the value of bucket_dict I get:
({'name': 'na1mailboxarchive', 'objectCount': 49564710, 'dataBytes': 36253526882451}, {'name': 'na1mailboxarchive2', 'objectCount': 17616567, 'dataBytes': 13409204616615})
I think the foul up is the () at the beginning and the end of the dictionary. Nothing else I have tried works either.
Try this instead
import ast
string = '{"name":"na1mailboxarchive","objectCount":49564710,"dataBytes":36253526882451},{"name":"na1mailboxarchive2","objectCount":17616567,"dataBytes":13409204616615}'
result = ast.literal_eval(string)
print(result)
result is returned as a dictionary
I got it figured out.
Firstly the json return from the REST API get is badly formatted. I will take that up with the vendor. Secondly I used some iof the infrmation form #PrashantKumar and #MisterMiyagi to sus out the issue I was having. In my original code I had loaded the list with:
bucket_info = [acct_string[acct_string_start+11:acct_len-4]]
The variable was capturing the leading "[" and trailing "]" as a part of the string. Once I removed them then the list behaved correctly and I now can work with it. Thank you for the information and the trail markers.
I want to use .find() like this for mongoDB in Python :
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27000')
db = client['responsi']
cursor = db['produk']
for x in cursor.find({"pricing.pct_savings":{"$gt":25}}).sort({"pricing.pct_savings":-1}):
print(x)
But, it showing error like this :
Traceback (most recent call last):
File "Find.py", line 7, in <module>
for x in cursor.find({"pricing.pct_savings":{"$gt":25}}).sort({"pricing.pct_savings":-1}):
File "G:\PROGRAM FILES\Python\lib\site-packages\pymongo\cursor.py", line 708, in sort
keys = helpers._index_list(key_or_list, direction)
File "G:\PROGRAM FILES\Python\lib\site-packages\pymongo\helpers.py", line 69, in _index_list
raise TypeError("if no direction is specified, "
TypeError: if no direction is specified, key_or_list must be an instance of list
How to solved this problem?
Thank you!
Sorry, I have bad score in english.
As opposed to the mongo shell, pymongo takes key and direction as the arguments to the sort method (or list, but that's another form that is not relevant to you currently, I'll show it too)
So your query should actually be cursor.find({"pricing.pct_savings":{"$gt":25}}).sort("pricing.pct_savings", pymongo.DESCENDING)
The other form gets a list of tuples of field name and the direction, and allows you to sort by multiple fields, for example collection.find().sort([('my_field_1',pymongo.DESCENDING), ('my_field_2',pymongo.ASCENDING)])
See the relevant documentation here https://api.mongodb.com/python/current/api/pymongo/cursor.html?highlight=sort#pymongo.cursor.Cursor.sort
You can find the ASCENDING and DESCENDING constants here https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.ASCENDING
BTW (not related to your original question)
db['produk'] is actually a collection, not a cursor, so it would be better if you would call it collection, and not cursor.
Cursor is what find() returns
should only have this structure
from bson import ObjectId
id = '375g68h97b680jf78j'
data = cursor.find_one_and_delete({'_id': ObjectId(id)})
I've built a sample code, to see if things worked as I wanted.
predictorgroups=predictor.groupby("sector")
targetco=target.iloc[1]
group=predictorgroups.get_group(targetco.sector).astype(object)
pdf=(group).sort('size',ascending=False)[:10].astype(object)
It worked fine. So I wanted to upgrade and make that code interact multiple times, so I adapted it to:
for i in range(len(target.index[:10])):
predictorgroups=predictor.groupby("sector")
targetco=target.iloc(i)
group=predictorgroups.get_group(targetco.sector).astype(object)
pdf=(group).sort('size',ascending=False)[:10].astype(object)
Note that this one is the very same code as the above. However in the second one I'm getting this error:
Traceback (most recent call last):
File "/file.py", line 64, in <module>
group=predictorgroups.get_group(targetco.sector).astype(object)
AttributeError: '_iLocIndexer' object has no attribute 'sector'
I noticed that in the first code, if I print targetco I get a Pandas Series with only one index. If I do the same in the second one, I get the following object type:
targetco pandas.core.indexing._iLocIndexer object at 0x105a3e438
Can anyone explain to me why is that happening? Why I'm getting a different response in the second code if they are both the same?
I think there is typo, change () to []:
targetco=target.iloc(i)
to
targetco=target.iloc[i]
Because:
targetco = target.iloc(1)
print (targetco)
<pandas.core.indexing._iLocIndexer object at 0x000000000A8CD358>
and then pandas.core.indexing._iLocIndexer object has no column sector, so raise error:
print (targetco.sector)
AttributeError: '_iLocIndexer' object has no attribute 'sector'
I have a dictionary with a single item in it created using json.loads(). The data structure looks like this:
{"teamId":96}
When I attempt to access the dictionary value by using the following:
mydict = mydict[u'teamId']
I get the following error:
Traceback (most recent call last):
File "C:\Python27\counter.py", line 65, in <module>
print home_team[u'teamId']
TypeError: string indices must be integers
Can anyone explain to me what the issue is here? The code looks like it should work to me.
Thanks
You need json.dumps(you_file) :
json.loads(json.dumps(your_file))