[英]Python looping through lists
我有一個名單:
word_list_pet_image = [['beagle', '01125.jpg'], ['saint', 'bernard', '08010.jpg']]
此列表中有更多數據,但我保持簡短。 我試圖遍歷此列表,並檢查該單詞是否只是字母字符,如果這是真的將該單詞附加到一個名為的新列表
pet_labels = []
到目前為止,我有:
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)
比如我試圖把這個詞beagle
進入榜單pet_labels,但跳過01125.jpg
。 見下文。
pet_labels = ['beagles', 'Saint Bernard']
我得到一個atributeError
AtributeError:'list'對象沒有屬性'isalpha'
我確信這與我沒有正確地遍歷列表有關。
看起來您正在嘗試在每個子列表中加入字母詞。 列表理解在這里是有效的。
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']
你有列表列表,所以蠻力方法是嵌套循環。 喜歡:
for pair in word_list_pet_image:
for word in pair:
if word.isalpha():
#append to list
另一個選項可能是單個for循環,但然后切片:
for word in word_list_pet_image:
if word[0].isalpha():
#append to list
word_list = [['beagle', '01125.jpg'], ['saint', 'bernard', '08010.jpg']]
為什么不list comprehension
(只有非所有字母字母元素總是在最后):
pet_labels = [' '.join(l[:-1]) for l in word_list]
word_list_pet_image.append(word.split("_"))
.split()
返回列表,因此word_list_pet_image
本身包含列表,而不是簡單的單詞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.