Simkill
Simkill

Reputation: 345

How to check if part of a class is part of list

I have a class that is populated by a random line from a previously determined list. The list is populated by a CSV file. The class looks like this:

class Gem:
    def __init__ (self, name, value):
        self.name = name
        self.value = float(value)

The lists populate correctly and Item is populated correctly using the class. I have 6 lists and I need to check if item.name is part of any of them. I thought:

if item.name in COMMONGEMS:
    item.value = random.range(4, 17)

I do this for each list, but whilst I don't get any errors, this doesn't ever get a match when it should.

How should I accomplish this instead?

Edit: In response to interjey, The list would look like this once loaded from the CSV:

print (COMMONGEMS)
[['Banded', '0'], ['Eye Agate', '0'], ['Moss Agate', '0'], ['Azurite', '0'], ['Blue quartz', '0'], ['Hematite', '0'], ['Lapis Lazuli', '0'], ['Malachite', '0'], ['Obsidian', '0'], ['Rhodochrosite', '0'], ['Tiger Eye', '0'], ['Turquoise', '0'], ['Freshwater', '0'], ['Irregular Pearl', '0']]

Upvotes: 0

Views: 85

Answers (2)

Serdalis
Serdalis

Reputation: 10489

Your current code is not checking the name within the list of lists. It is only checking the inner list itself which would not match your query. A simple loop can look into the inner list at the names:

for element in COMMONGEMS:
    if item.name == element[0]:
        item.value = random.range(4, 17)

I used == instead of in because there is probably a gem which has a name in another name, but is not that name. Such as ruby matching star ruby etc.

Upvotes: 2

elnabo
elnabo

Reputation: 264

If item.name is a string like "Banded", item.name won't be found in COMMONGEMS.

['Banded', '0'] in COMMONGEMS => true

'Banded' in COMMONGEMS => false

Edit: Instead of a list you can use a dictionary:

COMMONGEMS = {'Banded': '0' , 'Azurite' : '0'}

if item.name in COMMONGEMS:
    item.value = random.range(4, 17)

Upvotes: 2

Related Questions