简体   繁体   English

Python循环遍历列表

[英]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 . 比如我试图把这个词beagle进入榜单pet_labels,但跳过01125.jpg see below. 见下文。

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

I am getting a atributeError 我得到一个atributeError

AtributeError: 'list' object has no attribute 'isalpha' AtributeError:'list'对象没有属性'isalpha'

I am sure it has to do with me not iterating through the list properly. 我确信这与我没有正确地遍历列表有关。

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']

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循环,但然后切片:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM