Nick
Nick

Reputation: 674

Python looping through lists

I have a list called:

word_list_pet_image = [['beagle', '01125.jpg'], ['saint', 'bernard', '08010.jpg']]

There is more data in this list but I kept it short. I am trying to iterate through this list and check to see if the word is only alphabetical characters if this is true append the word to a new list called

pet_labels = []

So far I have:

word_list_pet_image = []
for word in low_pet_image:
    word_list_pet_image.append(word.split("_"))

for word in word_list_pet_image:
    if word.isalpha():
        pet_labels.append(word)
        print(pet_labels)

For example I am trying to put the word beagle into the list pet_labels, but skip 01125.jpg. see below.

pet_labels = ['beagles', 'Saint Bernard']

I am getting a atributeError

AtributeError: 'list' object has no attribute 'isalpha'

I am sure it has to do with me not iterating through the list properly.

Upvotes: 3

Views: 94

Answers (4)

U13-Forward
U13-Forward

Reputation: 71610

word_list = [['beagle', '01125.jpg'], ['saint', 'bernard', '08010.jpg']]

Why not list comprehension (only if non-all alphabetical letters element is always at last):

pet_labels = [' '.join(l[:-1]) for l in word_list]

Upvotes: 1

bphi
bphi

Reputation: 3195

It looks like you are trying to join alphabetical words in each sublist. A list comprehension would be effective here.

word_list = [['beagle', '01125.jpg'], ['saint', 'bernard', '08010.jpg']]

pet_labels = [' '.join(w for w in l if w.isalpha()) for l in word_list]

>>> ['beagle', 'saint bernard']

Upvotes: 3

Cobra
Cobra

Reputation: 632

You have lists of lists, so the brute force method would be to nest loops. like:

for pair in word_list_pet_image:
    for word in pair:
        if word.isalpha():
            #append to list

Another option might be single for loop, but then slicing it:

for word in word_list_pet_image:
    if word[0].isalpha():
        #append to list

Upvotes: 1

John Gordon
John Gordon

Reputation: 33351

word_list_pet_image.append(word.split("_"))

.split() returns lists, so word_list_pet_image itself contains lists, not plain words.

Upvotes: 0

Related Questions