简体   繁体   English

从列表中删除包含小写字母和null的元素

[英]Remove elements contains lowercase & null from list

I have a list that contains words, numbers & some random characters.I want to remove elements that contain other than UPPERCASE, Punctuation & Digits. 我有一个包含单词,数字和一些随机字符的列表。我想删除除大写,标点和数字之外的其他元素。

list_of_words =  ['S I NGHVI', '', 'MGANPAT', '/', '', '', 'q', 'gq6', '14', 'A -_']
for i in list_of_words:
    for j in i:
        if ord(j) not in range(65,91): # for shortlisting A-Z ascii values
            del list_of_words[i]

is throwing me error like this: TypeError: list indices must be integers or slices, not str 给我这样的错误: TypeError: list indices must be integers or slices, not str

Output I want: 我想要的输出:

list_of_words = ['S I NGHVI', 'MGANPAT', '/', '14', 'A -_']

Answer for first version of question 第一个问题的答案

To get "only CAPITAL letter words & numbers" : 要获取“仅大写字母的单词和数字”

>>> [w for w in list_of_words if w.isupper() or w.isdigit()]
['S I NGHVI', 'MGANPAT', '14', 'A -_']

Simply do the following: 只需执行以下操作:

from string import *
list_of_words = [word for word in list_of_words if all([letter in punctuation+ascii_uppercase+digits+' ' for letter in word]) and word]

>>> from string import *                                                        
>>> list_of_words =  ['S I NGHVI', '', 'MGANPAT', '/', '', '', 'q', 'gq6', '14', 'A -_']
>>> list_of_words = [word for word in list_of_words if all([letter in punctuation+ascii_uppercase+digits+' ' for letter in word])]
>>> list_of_words
['S I NGHVI', 'MGANPAT', '/', '14', 'A -_']
>>> 

You have a couple issues in your code: 您的代码中有几个问题:

  1. Do not use del to remove from a list, you can use .remove() , .pop() , or simply overwrite the list. 不要使用del从列表中删除,可以使用.remove() .pop()或简单地覆盖列表。
  2. list_word is not defined, perhaps you meant list_of_words ? list_word没有定义,也许您是说list_of_words吗?
  3. Using ord is not as readable and concise as using the string module. 使用ord不如使用string模块那么可读和简洁。 Simply import string and call dir(string) to see the various predefined character sets you can access. 只需import string并调用dir(string)即可查看您可以访问的各种预定义字符集。
  4. You are using is wrong; 您使用的is错误的; is compares the id s of two objects. is比较两个对象的id In this case, you can simply omit it and use not in . 在这种情况下,您可以简单地省略它, not in使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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