简体   繁体   English

在Python列表中删除没有数字的单词的方法是什么?

[英]What is the way to delete words in Python list which does not have numbers?

 a = ['in 1978 by', 'History', 'members', 'albums', 'June 4th, 1979', 'October 7,1986): "The Lounge', 'In 1984 the', 'early 1990s; prominent']

the above list have words like history, members which do not have numbers in them, so i want to delete them 上面的列表有像历史,成员没有数字的单词,所以我想删除它们

 # output would be
 a = ['in 1978 by', 'June 4th, 1979', 'October 7, 1986', 'In 1984 the', 'early 1990s; prominent']

Keep the ones you want: 保留你想要的:

a = ['in 1978 by', 'History', 'members', 'albums', 'June 4th, 1979', 'October 7,1986): "The Lounge', 'In 1984 the', 'early 1990s; prominent']

new = [el for el in a if any(ch.isdigit() for ch in el)]
# ['in 1978 by', 'June 4th, 1979', 'October 7,1986): "The Lounge', 'In 1984 the', 'early 1990s; prominent']

Here's a shorter alternative, using any() and string.digits : 这是一个较短的替代方案,使用any()string.digits

from string import digits

a = ['in 1978 by', 'History', 'members', 'albums', 'June 4th, 1979', 
     'October 7,1986): "The Lounge', 'In 1984 the', 'early 1990s; prominent']

[x for x in a if any(y in x for y in digits)]

=> ['in 1978 by', 'June 4th, 1979', 'October 7,1986): "The Lounge',
    'In 1984 the', 'early 1990s; prominent']

Using a regular expression and a list comprehension, this is a one-liner: 使用正则表达式和列表理解,这是一个单行:

import re
[i for i in a if re.search('\d', i) is not None]

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

相关问题 删除包含 2 个连续元音的单词 - Delete words which have 2 consecutive vowels in it 有没有办法将一串数字和单词更改为嵌套列表,其中名称与 Python 中的各个数字相关联? - Is there a way to change a string of numbers and words into a nested list, where the name are associated with their individual numbers in Python? 我正在寻找在 python 中嵌套数字列表的快捷方式? - I am looking for short way to have nested list of numbers in python? Python:如何删除列表中的数字 - Python: How to delete numbers in list Python-将数字更改为单词的最简单方法 - Python - Easiest way to change numbers to words 列表中有数字吗? - Does the list have any numbers? 如何从 python 中的变量中删除某些单词和数字 - how can i delete certain words and numbers from a variable in python 有没有办法使用列表中的python来分类/删除单词(例如,“哪个”,“潜在”,这个,“是”等) - Is there any way to classify/ remove words (Exm. “Which”, “potential”, this, “are” etc.) using python from a list 这个 Python 代码用简单的语言有什么作用? - What does this Python code does in plain words? python是否有更好的方法来拆分字符串而不是转换为列表? - Does python have a better way to split a string than converting to a list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM